我想将从Ajax传递到PHP的数组保存到表的不同列。
以下是Ajax发送给PHP的数组:
单击保存按钮后,我在浏览器网络标题上显示此内容。
表格数据:
tableArray[0][]:awdawd
tableArray[0][]:awdawd
tableArray[0][]:Male
tableArray[0][]:<button class='delete'>Delete</button>
tableArray[1][]:awdaw
tableArray[1][]:awdwa
tableArray[1][]:Female
tableArray[1][]:<button class='delete'>Delete</button>
我的问题是在点击保存按钮后,它只将数组的名称部分保存到表中:
脚本:
$("#saveTable").click(function(){
$.ajax(
{
url: "saveTable.php",
type: "POST",
data: { tableArray: dataSet},
success: function (result) {
}
});
});
saveTable.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$tableArray = $_REQUEST['tableArray'];
foreach( $tableArray As $v){
$sql = "INSERT INTO viewTables (name, age, gender, action) VALUES ('$v[0]','$[1]','$[2]','$[3]')";
$query = $dbc->prepare($sql);
$query->execute();
}
?>
答案 0 :(得分:1)
$sql = "INSERT INTO viewTables (name, age, gender, action) VALUES ('$v[0]','$[1]','$[2]','$[3]')";
应该是
$sql = "INSERT INTO viewTables (name, age, gender, action) VALUES ('$v[0]','$v[1]','$v[2]','$v[3]')"; // Added array name for the last three values
答案 1 :(得分:1)
@Sadiq指出了这个问题,这只是一个错字。但是,我建议您实际使用预处理语句,只需准备一次语句并使用参数来防止SQL注入。
$sql = "INSERT INTO viewTables (name, age, gender, action) VALUES (:name, :age, :gender, :action)";
try {
$sth = $dbc->prepare($sql);
foreach( $tableArray As $v){
// bind parameter values
$sth->bindValue(':name', $v[0], PDO::PARAM_STR);
$sth->bindValue(':age', $v[1], PDO::PARAM_STR);
$sth->bindValue(':gender', $v[2], PDO::PARAM_STR);
$sth->bindValue(':action', $v[3], PDO::PARAM_STR);
$sth->execute();
}
} catch (PDOException $e) {
// something went wrong
// log an error or whatever
}