php - 错误插入多个值数据库 php

标签 php jquery html css sql

有人能解释一下为什么这不起作用吗,我试图将多个值插入数据库,首先我只插入了 carpirces 并且正在工作,但现在我也尝试插入 de IDs 但现在代码不起作用

if(!empty($_POST))
{ 
  $query = "INSERT INTO prices (carid, vendorid, carprice) values (:carid, 2, :carprice)";
  $query_params = array(':carprice' => $_POST['carprice']);
  $price = null;
  $carids = null;
  try
  {
    $stmt = $db->prepare($query); 
    $stmt->bindParam(':carprice', $price);  
    foreach($_POST['carprice'] as $value) { 
            $price = $value;
            $stmt->execute();
    }
      $stmt->bindParam(':carid', $carids);  
    foreach($_POST['carid'] as $value) { 
            $carids = $value;
            $stmt->execute();
    }

  }
  catch(PDOException $ex)
  {
    die("Error 1 " . $ex->getMessage());
  } 
  header("Location: update.php");
  die("Rendirecting to update.php");
}
?>
<form action="prices.php" method="post">
<table border=1>
  <tr>
    <th>Id</th>
    <th>car</th>
    <th>model</th>
    <th>Price</th>
  </tr>
<?php foreach($rowscars as $row): ?>
  <tr>
    <th><input type="hidden" name="carid[]" value="<?php echo ' ' . htmlentities($row['carid'], ENT_QUOTES, 'UTF-8') . ' ';?>" /><?php echo '' . htmlentities($row['carid'], ENT_QUOTES, 'UTF-8') . '';?></th>
    <th><?php echo '' . htmlentities($row['car'], ENT_QUOTES, 'UTF-8') . '';?></th>
    <th><?php echo '' . htmlentities($row['model'], ENT_QUOTES, 'UTF-8') . '';?></th>

    <th><input type="text" name="carprice[]" value=""></th>
  </tr>
<?php endforeach; ?>
</table>
<input type="submit" value="Submit">
</form> 

最佳答案

我想您要为指定的 carId 插入 carPrice。首先,您需要将每个汽车 ID 映射到汽车价格,像这样做:

if (!empty($_POST['carid'] && $_POST['carprice']) {
   $carPrices = array_combine($_POST['carid'], $_POST['carprice']);
   foreach ($carPrices as $carId => $carPrice) {
      $stmt = $db->prepare($query); 
      $stmt->bindParam(':carprice', $carPrice);
      $stmt->bindParam(':carid', $carId);
      $stmt->execute();
   }
}

关于php - 错误插入多个值数据库 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23317164/

相关文章:

PHP 和 PostgreSQL - 从 SQL 文件插入行

php - 添加 'x' 迄今为止的小时数

php - 如果 UserAgent 是 iPhone,则动态更改 url 或 WordPress 主题

jquery - jquery 问题 - 将太长的文本替换为 "..."

javascript - 使用 WP UI 从选项卡到选项卡的 Jquery 文本链接

jquery - 使用在需要时通过 $.post 将信息发送到服务器的 jquery 开发网站有什么缺点吗?

javascript - 按钮在表格中不起作用?

php - 如何在 PHP 中创建合适的相册应用程序?

JavaScript 欧盟 cookie 法横幅未删除

PHP 为中间的每个框着色