我想在数据库中插入两个数组和其他值,目前我正在使用bindValue
保存它们并使用foreach迭代这两个数组。
的Ajax
$rows.each(function() {
var $tds = $(this).find('td');
var namesport = $tds.eq(0).text();
var time = $tds.eq(1).text();
var date = $tds.eq(2).text();
valueToPush1.push({
sportname: namesport,
time: time,
date: date,
});
});
var valueToPush = [];
$rows.each(function() {
var $tds = $(this).find('td');
var subjectname = $tds.eq(0).text();
var time = $tds.eq(1).text();
var date = $tds.eq(2).text();
valueToPush.push({
namesubject: subjectname,
time: time,
date: date,
});
});
var sports = JSON.stringify(valueToPush);
var class = JSON.stringify(valueToPush1);
$.ajax({
type: 'POST',
url: '../include/studentactivities.php',
dataType: "json",
data: {
id: studentid,
sports: sports,
class: class,
},
从这个ajax我把它发送到PHP,我在那里插入文件。这是我被困的地方,我用完了如何将这两个数组与其他信息一起保存的想法。我将这两个数组保存在每个表中,如下所示
PHP
$sports = ($_POST['sports']);
$sportsjson = json_decode(stripslashes($sports), true);
$class = ($_POST['class']);
$classjson = json_decode(stripslashes($class), true);
$id = ($_POST['id']);
if (isset($id)) {
$sportsarray = array();
$classarray = array();
foreach($sports as $value) {
$sportsarray[] = array(
'sport' => $value['sportname'],
'stime' => $value['time'],
'sdate' => $value['date']);
}
foreach($classjson as $value1) {
$classarray[] = array(
'subject' => $value1['subjectname'],
'ctime' => $value1['time'],
'cdate' => $value1['date']);
}
$aray = array_merge($sportsarray, $classjson);
//echo json_encode($aray, JSON_UNESCAPED_UNICODE);
foreach($aray as $value) {
$stmt = $dbh - > prepare("INSERT INTO sports_tbl (sport_name,time,date) VALUES (?,?,?)");
$stmt - > bindValue(1, $value['sport'], PDO::PARAM_STR);
$stmt - > bindValue(2, $value['stime'], PDO::PARAM_STR);
$stmt - > bindValue(3, $value['sdate'], PDO::PARAM_LOB);
$stmt1 = $dbh - > prepare("INSERT INTO class_tbl (class_name,time,date) VALUES (?,?,?)");
$stmt1 - > bindValue(1, $value['class'], PDO::PARAM_STR);
$stmt1 - > bindValue(2, $value['ctime'], PDO::PARAM_STR);
$stmt1 - > bindValue(3, $value['cdate'], PDO::PARAM_STR);
if ($stmt - > execute() && $stmt1 - > execute()) {
echo json_encode($aray, JSON_UNESCAPED_UNICODE);
} else {
echo "Not added";
}
}
}
问题是我得到错误。当我删除插入sql并返回json_eoncode
时,我得到双重结果。在pdo中执行此类插入的更简洁方法是什么?