错误插入多个值数据库php [英] error inserting multiple values database php
本文介绍了错误插入多个值数据库php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以解释我为什么这不工作,我试图插入多个值到数据库,首先我只插入carpirces,并正在工作,但现在我想插入也de ID,但现在的代码不工作
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
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映射到汽车价格,这样做:
I suppose you want to insert carPrice for specified carId. First you need to map each car id to car price, do smth like this:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文