1

I'm trying to create a function where a user should select an option from a <select> and add a date to the value selected (inside <input type='text'> on the same row). Then when the fields have been inputted send as an array to a PHP file and inserted to a database.

I'm creating the <select>, and <input type='text'> dynamically on the same row in a table.

Selects look something like this: <input type='select' class='add_absence_type'>
Input fields: <input type='text' class='add_absence_date'>

The script I'm working on looks like this at the moment:

$('#save').click(function() {
function serealizeSelects (select)
    {
        var array = [];
        select.each(function(){ array.push($(this).val()) });
        return array;
    }
function serealizeInputs (input)
    {
        var array = [];
        input.each(function(){ array.push($(this).val()) });
        return array;
    }
    var student_id = $('#student_id').val();
    var add_absence_type = serealizeSelects($('.add_absence_type'));
    var add_absence_date = serealizeInputs($('.add_absence_date'));

    $.post('../updateAbsence.php', {

    student_id: student_id,
    add_absence_type: add_absence_type,
    add_absence_date: add_absence_date

    }, function(data) {
        location.reload();
    });
});

The $_POST data looks like this:

student_id  1
add_absence_date[]  2012-11-13
add_absence_date[]  2012-11-14
add_absence_type[]  1
add_absence_type[]  2

What do I need to do to create a PHP loop that creates mysql_query's like this? See below:

"INSERT INTO my_table (student_id, absence_type_id, absence_date) VALUES ('1', '1', '2012-11-13')"

"INSERT INTO my_table (student_id, absence_type_id, absence_date) VALUES ('1', '2', '2012-11-14')"

1
  • foreach($_POST['add_absence_date'] as $key=>$value){..} you can use this way and build query into foreach Commented Nov 14, 2012 at 8:27

1 Answer 1

1

Try this way

<?php
$student_id = $_POST['student_id'] ;
$absence_date_arr = $_POST['add_absence_date'] ;
$absence_type = $_POST['add_absence_type'] ;

foreach($absence_date_arr as $key=> $absence_date){
    mysql_query("INSERT INTO my_table (student_id, absence_type_id, absence_date) VALUES ('".$student_id."', '".$absence_type[$key]."', '".$absence_date."')");  
}
?>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.