简体   繁体   中英

Passing multidimensional array to php via ajax

I am trying to pass a multidimensional array from my jquery script to a php file which writes the values in the array to a mysql table. Here are my efforts so far but data is not inserted into the table. Any help appreciated.

sourceblockstaffarray structure:

|Userid|staffid|blockid|

with multiple rows so an example of the content of the array would be

|1|2|3|

|4|5|6|

|7|8|9|

Ajax:

 $.ajax

 ({

    url: 'tl2_post_staffonblock_via_array.php',
    cache: false,
    type: 'POST',
    dataType: 'html',
    data: {staffarray: JSON.stringify(sourceblockstaffarray)},              
    success: function(data)
    {                   
    },
    error: function(data)
    {   
    }                   
}); 

php:

<?php

include ('tl2_config.php');

$conn = mysqli_connect($HOST_STRING, $USER_NAME, $USER_PASSWORD, $DATABASE_NAME);

$staffarray = json_decode( $_POST['staffarray'] );

foreach($staffarray as $m)
{
  $userid    = $m[0];
  $staffid   = $m[1];
  $blockid   = $m[2];
  $stmt = mysqli_prepare($conn, "INSERT INTO staffonblock (userid, 
  staffid, blockid) VALUES (?, ?, ?)");
  mysqli_stmt_bind_param($stmt, "sss",  $userid, $staffid, $blockid);
  mysqli_stmt_execute($stmt);
}
?>

By the looks of it you need json_decode to change the json array to an array that PHP can iterate through.

$staffarray = json_decode( $_POST['staffarray'] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM