php - 多值写入数据库php、sql

标签 php html mysql css sql

谁能解释一下我该如何修改这段代码,以便我能够插入多个值,而不仅仅是第一个值。

 $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/

相关文章:

php - 提交按钮在 IE/Safari 中不起作用,在 Chrome 中起作用并且信息被传递

php - 按长度排序数组,然后按字母顺序排序

javascript - 单击某个选项,然后将值传递给链接到唯一 url 的 "buy now"按钮

php - 输入字段 : store decimal values with comma instead of a point in mysql database

mysql - MySQL 中用户定义变量的奇怪行为

php - Magento TopLinks 作为悬停时的下拉菜单

php - 从表中查询记录,其中 attribute = items from array from previous query

php - 在我们获取和显示数据的PHP中,删除按钮不起作用吗?

javascript - HTML 或 CSS 导航栏问题

php - 如何解决 codeigniter 中 MySql 查询语法中的这个错误?