PDO在foreach循环中更新行值
问题描述:
我在foreach循环内创建了一个表,在表中显示了所有记录。然后我包含一个SQL更新与选择和更新一个数组值。当我选择不同的值时,循环会更新表中的所有记录,而不是只有一个被更新。我整天都在苦苦挣扎,请帮助我。PDO在foreach循环中更新行值
如果foreach是错误的方式,我将非常感谢您对如何显示可显示记录并允许更新每个阵列的表的建议。
<?php
foreach ($stmt as $key => $row)
{
$newcustomerid = htmlentities($row['customer_id']);
echo '<tr><td>' . htmlentities($row['customer_company']) . '</td>';
echo '<td> id:' . $newcustomerid . 'key: ' . $key .'</td>';
echo '<td>' . htmlentities($row['customer_email']) . '</td>';
echo '<td>' . htmlentities($row['customer_phone']) . '</td>';
echo '<td>' . htmlentities($row['customer_country']) . '</td>';
echo '<td>' . htmlentities($row['customer_city']) . '</td>';
echo '<td>' . htmlentities($row['customer_segment']) . '</td>';
echo '<td>' . htmlentities($row['customer_updated']) . '</td>';
$customer_status = htmlentities($row['customer_status']);
if(isset($_POST['Submitbb'])){ //check if form was submitted
$input = $_POST['Submitbb']; //get input text
$stmtUpdateStatus = $conn->prepare("UPDATE user_customers SET `customer_status` = :customer_status WHERE `customer_id` = :customer_id");
$stmtUpdateStatus->execute(array(':customer_status' => $input, ':customer_id' => $row['customer_id']));
}
echo '<td>
<form action="" method="post">
<select name="Submitbb" onchange="this.form.submit();">
<option> - ' . $customer_status . ' - </option>
<option>Susisiekti</option>
<option>Priminimas 1</option>
<option>Priminimas 2</option>
<option>Paskambinti</option>
<option>Netinkamas klientas</option>
</select>
</form>
</td>';
echo '<td>' . 'Išsaugoti' . '</td></tr>';
}
?>
谢谢。
答
你可以使用一个隐藏的输入捕捉行中的数据库要更新
echo '<td>
<form action="" method="post">
<input name="customer_id" type="hidden" value="'.$newcustomerid.'"/> <!-- hidden -->
<select name="Submitbb" onchange="this.form.submit();">
<option> - ' . $customer_status . ' - </option>
<option>Susisiekti</option>
<option>Priminimas 1</option>
<option>Priminimas 2</option>
<option>Paskambinti</option>
<option>Netinkamas klientas</option>
</select>
</form>
</td>';
然后进行比较时的形式张贴
if(isset($_POST['Submitbb'])){ //check if form was submitted
$input = $_POST['Submitbb']; //get input text
$customer_id = $_POST['customer_id']; // get the posted customer ID
if($row['customer_id'] == $customer_id){
$stmtUpdateStatus = $conn->prepare("UPDATE user_customers SET `customer_status` = :customer_status WHERE `customer_id` = :customer_id");
$stmtUpdateStatus->execute(array(':customer_status' => $input, ':customer_id' => $customer_id));
}
}
谢谢!但是..它说:“未定义的索引:customer_id”在您张贴的第二个代码块的第三行。 – Lukas
嘿,采取两个块的新副本,我做了几个编辑,其中一个修复该错误 – andrew
谢谢,我现在就试试。 – Lukas