简体   繁体   English

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

[英]error inserting multiple values database php

Can someone explain me why this is not working, Im trying to insert multiple values into a database, first I was inserting carpirces only and was working, but now Im trying to insert also de Ids but now the code don't work 有人可以解释一下为什么这行不通吗,我试图将多个值插入数据库,首先我只插入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> 

I suppose you want to insert carPrice for specified carId. 我想您想为指定的carId插入carPrice。 First you need to map each car id to car price, do smth like this: 首先,您需要将每个汽车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();
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM