2014-03-12 112 views
0

我有从一种形式的文本框我的交值例如:选择在MySQL与匹配ID阵列的阵列,并计算

<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=""/> 
在我的PHP代码

$id = $_POST['m_id']; 
$qty = $_POST['qty']; 

让我们假设后阵列有值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中的qty数组输入1,1,1中减去余额。

+2

我最初的猜测是查询。 –

+0

究竟这个数量的1是如何影响你的数据的?您的余额在两个表格之间没有变化。你所做的只是消除一些不存在于ID中的行。 –

+0

你需要得到减法的结果吗?否则你可以做一个'UPDATE'查询 – MamaWalter

回答

0

您需要为每个id更新查询的循环。你没有提到数据库连接风格,所以我将使用PDO。注意:此代码假定每个ID都有一个数字。您还需要更新更新语句以匹配您的数据库名称等...

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(); 
} 
+0

你为什么只绑定一个参数? – MamaWalter

+0

良好的通话!这将打开它的SQL注入,现在不是吗?将编辑答案... – larsAnders