请您查看以下代码段,让我知道为什么我无法将数组值插入数据库。在Js文件中我有:
<script>
var arr = ["foo", "2015/11/04", "Jill", "Smith", "60"];
var serializedArr = JSON.stringify( arr );
$("#loader").on("click", function(){
var upload = $.ajax({
type: "POST",
url: "loader.php",
data: {array:serializedArr},
cache: false,
beforeSend: function() {
}
});
});
并在PHP文件中
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASSWORD', '' );
define ( 'DB_NAME', 'dbapp' );
//$array = json_decode($_POST['array']);
$array = $_POST['array'];
//Open a new connection to the MySQL server
$mysqli = new mysqli('DB_HOST','DB_USER','DB_PASSWORD','DB_NAME');
$arr_one = $mysqli->real_escape_string($array[0]);
$arr_two = $mysqli->real_escape_string($array[1]);
$arr_three = $mysqli->real_escape_string($array[2]);
$arr_four = $mysqli->real_escape_string($array[3]);
$arr_five = $mysqli->real_escape_string($array[4]);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO `models` (name, date, nip, tip, age) VALUES($arr_one, $arr_two, $arr_three, $arr_four, $arr_five)");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
// close connection
$mysqli->close();
?>
我试过了两次
$array = json_decode($_POST['array']);
和
$array = $_POST['array'];
但是我无法加载数据,甚至没有错误信息在页面上?!
答案 0 :(得分:1)
问题是你在通过AJAX请求发送数组之前是JSON.stringify&#39。这意味着阵列=&#34; [&#34; foo&#34;,&#34; 2015/11/04&#34;,&#34; Jill&#34;,&#34; Smith&#34;,& #34; 60&#34;]&#34;,这在技术上不是有效的JSON对象。
尝试将数组包装在js对象中,然后对其进行字符串化。比如
var arr = {data: ["foo", "2015/11/04", "Jill", "Smith", "60"] };
然后尝试
$array = json_decode($_POST['array']).data;
答案 1 :(得分:1)
success
,error
句柄,将结果/错误输出到控制台。因此,在使用之前,您需要json_decode
收到的数据。
$array = json_decode( $_POST['array'] );
$mysqli = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
$insert_row_stmt = $mysqli->prepare( "INSERT INTO `models` (name, date, nip, tip, age) VALUES(?, ?, ?, ?, ?)");
$insert_row_stmt->bind_param( 'ssssi',
$array[0],
$array[1],
$array[2],
$array[3],
$array[4]
);
$insert_row = $insert_row_stmt->execute();
var upload = $.ajax({
type: "POST",
url: "loader.php",
data: {array:serializedArr},
cache: false,
success: function(d) {
console.log(d);
}
});
答案 2 :(得分:0)
<div id="loader"></div>
<script src="jquery.min.js"></script>
<script>
var arr = ["foo", "2015/11/04", "Jill", "Smith", "60"];
$("#loader").load('load.php',{arr:arr});
</script>
load.php:
<?php
$arr = $_POST['arr'];
$insert_row = $mysqli->query("INSERT INTO `models` (name, date, nip, tip, age)
VALUES($arr[1], $arr[2], $arr[3], $arr[4], $arr[5])");
?>
您可以在数据库中添加这样的值。