Php 在mysql中选择一个具有匹配id数组的数组并计算
我有一个表单文本框中的post value示例:Php 在mysql中选择一个具有匹配id数组的数组并计算,php,mysql,select,Php,Mysql,Select,我有一个表单文本框中的post value示例: <input type="number" name="m_id[<?php echo $row['m_id']; ?>]" value="<?php echo $row['m_id']; ?>"/> <input type="number" name="qty[<?php echo $row['m_id']; ?>]" value=""/> 假设post数组的值id为2,4,5,数量
<input type="number" name="m_id[<?php echo $row['m_id']; ?>]" value="<?php echo $row['m_id']; ?>"/>
<input type="number" name="qty[<?php echo $row['m_id']; ?>]" value=""/>
假设post数组的值id为2,4,5,数量输入为1,1,1
id qty
2 1
4 1
5 1
如何选择名为sup_mon的表,如:
sup_mon table:
m_id balance
1 2
2 5
3 20
4 15
5 8
the select will be:
m_id balance
2 5
4 15
5 8
如何从相应m_id中的数量数组输入1,1,1中减去余额。您需要一个循环,每个id都有一个更新查询。您没有提到数据库连接样式,因此我将使用PDO。注意:此代码假定每个id都有一个数量。您还需要更改update语句以匹配您的数据库名称,等等
for ($i=0; $i<count($_POST['id']); $i++) {
$sql = "UPDATE databaseName.sup_mon SET balance = balance - :qty WHERE m_id = :id";
//if you're debugging, you may want to uncomment the next line:
//echo $sql;
//here $dbh is a PDO object - database handler
$stmt = $dbh->prepare($sql);
//binds the current id value from the post array
$stmt->bindParam(':id', $_POST['id'][$i], PDO::PARAM_INT);
$stmt->bindParam(':qty', $_POST['qty'][$i], PDO::PARAM_INT);
$stmt->execute();
}
用于($i=0;$iMy最初的猜测可能是一个查询。1的数量究竟会如何影响您的数据?您在两个表之间的余额不会发生变化。您所做的只是删除id中不存在的一些行。您需要获得减法的结果吗?否则您可以只执行更新
查询您想只进行d吗我在屏幕上显示差异,还是要从数据库中的余额中减去值?是的,我需要它来更新另一个表..请帮助。为什么只绑定一个参数?很好的调用!这将打开sql注入,不是吗?将编辑答案。。。
for ($i=0; $i<count($_POST['id']); $i++) {
$sql = "UPDATE databaseName.sup_mon SET balance = balance - :qty WHERE m_id = :id";
//if you're debugging, you may want to uncomment the next line:
//echo $sql;
//here $dbh is a PDO object - database handler
$stmt = $dbh->prepare($sql);
//binds the current id value from the post array
$stmt->bindParam(':id', $_POST['id'][$i], PDO::PARAM_INT);
$stmt->bindParam(':qty', $_POST['qty'][$i], PDO::PARAM_INT);
$stmt->execute();
}