谁能解释一下我该如何修改这段代码,以便我能够插入多个值,而不仅仅是第一个值。
$aid = $_SESSION['assignmentid']; //Assignment id
$query = "INSERT INTO studentgrade (studentid, assignmentid, studentpoints) values (:studentid, '$aid' , :studentpoints)";
$query_params = array(':studentpoints' => $_POST['studentpoints'], ':studentid' => $_POST['studentid']);
$points = null;
$studentids = null;
try
{
$carPrices = array_combine($_POST['studentpoints'], $_POST['studentid']);
$stmt = $db->prepare($query);
$stmt->bindParam(':studentid', $studentids);
$stmt->bindParam(':studentpoints', $points);
foreach ($carPrices as $points => $studentids) {
$stmt->execute();
}
}
catch(PDOException $ex)
{
die("Error 1 " . $ex->getMessage());
}
最佳答案
$aid = $_SESSION['assignmentid'];
$query = "INSERT INTO studentgrade (studentid, assignmentid, studentpoints) values ";
$carPrices = array_combine($_POST['studentpoints'], $_POST['studentid']);
$v = array();
foreach($carPrices as $a => $b) {
$v[] = "('$a', '$aid', '$b')";
}
$query .= implode(', ', $v);
$query 将是“INSERT INTO studentgrade (studentid, assignmentid, studentpoints) values (point1, aid, id1), (point2, aid, id2), [...”
关于php - 多值写入数据库php、sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23319515/