cpardon
cpardon

Reputation: 485

Insert Into MySQL from Dynamic Array sent through Ajax

UPDATED Solution

I realised that sending this array should NOT be this complicated. I went back and revised my original jquery script to push() the [] items.

var seqImg = new Array();
    $('input[name="seqImg[]"]').each( function() {
        seqImg.push($(this).val());
    } );

With the ajax, I used an data: {seqImg:seqImg} with the additional configuration of async:false to ensure the sequence stayed in correct order.

In the PHP...

$sql= "INSERT INTO  unit_test(`unit_id`,`seq_img`) VALUES ";            

              $i=0;
              $seqImgs_count = count($seqImgs);

              //$data = $seqImgs_count;
              //echo $data;

              foreach($seqImgs as $item) {

                  $end = ($i == $seqImgs_count-1) ? ';' : ',';

                  $sql .= "('".$unit_id1."','".$item."')".$end;

It works!

Original Message (for what its worth...)

I am trying to collect a set of sequences that are to be dynamically generated by the user.

So far, I've emulated AustinAllover's answer. This seems to have gotten me close, but not quite there.

The PHP

// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
    or die ('Error connecting to MySQL server.');


    if(isset($_POST["result"])){ 
        $json       =   trim($_POST['result']);
        $item_array =   json_decode($json,true);

        // Begin building the query
        // ------------------------
        $sql= "INSERT INTO  unit_test (`unit_id`,`seq_img`,`seq_desc`) VALUES ";            

        $i=0;
        $array_count = count($item_array);

            // ------------------------
            // NOTE: I've echo'd $array_count
            //...it is showing `1`
            //...but it is supposed to be 3
            // ------------------------

        $data = $array_count;
        echo $data;

        foreach($item_array as $item) {

            // Create comma or semi-colon       
            $end = ($i == $array_count) ? ';' : ',';

            // Build each row of data to insert
            $sql .= "('".$item['unit_id']."','".$item['array_seq_image']."','".$item['array_seq_desc']."')".$end;
            $i++;
                }
        mysqli_query($dbc,$sql)
            or die('Error with INSERT. '.$sql);

        mysqli_close($dbc);

The Fiddle

The alert shares the seq_array sent via Ajax data: {result:JSON.stringify(seq_array)}, I've included the example Jquery/Ajax: jsFiddle

The Result

Jquery Alert is showing the array sent:

"{"0":{"unit_id":1","ajax_seq_image":"111","ajax_seq_desc":"sample1"},"1":{"unit_id":1","ajax_seq_image":"222","ajax_seq_desc":"sample2"},"2":{"unit_id":1","ajax_seq_image":"333","ajax_seq_desc":"sample3"}}"

Console is showing me the following result from the query attempt:

<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/cpardonc/public_html/mw/test_form_process2.php</b> on line <b>32</b><br />
Error with INSERT. INSERT INTO  unit_test (`unit_id`,`seq_img`,`seq_desc`) VALUES 

Upvotes: 1

Views: 1230

Answers (2)

cpardon
cpardon

Reputation: 485

In case you missed the UPDATED SOLUTION posted at the start of the original question... I realised that sending this array should NOT be this complicated. I went back and revised my original jquery script to push() the [] items.

var seqImg = new Array();
$('input[name="seqImg[]"]').each( function() {
    seqImg.push($(this).val());
} );

With the ajax, I used an data: {seqImg:seqImg} with the additional configuration of async:false to ensure the sequence stayed in correct order.

In the PHP...

$sql= "INSERT INTO  unit_test(`unit_id`,`seq_img`) VALUES ";            

          $i=0;
          $seqImgs_count = count($seqImgs);

          //$data = $seqImgs_count;
          //echo $data;

          foreach($seqImgs as $item) {

              $end = ($i == $seqImgs_count-1) ? ';' : ',';

              $sql .= "('".$unit_id1."','".$item."')".$end;

It works!

Upvotes: 0

KA.
KA.

Reputation: 4504

You json is not well formatted. You missed a " .

it should be like this

{"0":{"unit_id":"1","ajax_seq_image":"111","ajax_seq_desc":"sample1"},"1":{"unit_id":"1","ajax_seq_image":"222","ajax_seq_desc":"sample2"},"2":{"unit_id":"1","ajax_seq_image":"333","ajax_seq_desc":"sample3"}}

But it is like this.

{"0":{"unit_id":1","ajax_seq_image":"111","ajax_seq_desc":"sample1"},"1":{"unit_id":1","ajax_seq_image":"222","ajax_seq_desc":"sample2"},"2":{"unit_id":1","ajax_seq_image":"333","ajax_seq_desc":"sample3"}}

see the difference?

Upvotes: 2

Related Questions