插入多个值数据库php时出错

时间:2014-04-26 22:25:31

标签: 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> 

1 个答案:

答案 0 :(得分:1)

我想你想为指定的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();
   }
}