![](/img/trans.png)
[英]how to update a table and insert a new record to another table in one query?
[英]How to INSERT in one table and UPDATE in another in single QUERY?
我当前正在创建某种库存系统。
我有master_tbl
,将项目保存在哪里。 在master_tbl
,我有qty_left
列或剩余可用库存。
我还有一张表issuance_tbl
,其中所有交易都保存在发行项目中。 在此表中有issued_qty
。
我的问题是如何在更新master_tbl.qty_left
的同时将一行插入到issuance_tbl
中。 (master_tbl.qty_left-issuance_tbl.issued_qty)。
可能吗?
我认为最好的方法是使用存储过程。 您可以在一堆中包含一堆带有错误处理和ACID事务的SQL语句。 这是因为如果第一个查询执行而第二个失败,则可能需要回滚事务。 存储过程允许所有这些花哨但可靠的东西。
您可以从这里开始: http : //forums.mysql.com/read.php?98,358569
这是示例:
<form method="post">
QTY:<input type="text" name="qty_left"></input>
<input type="submit" name="submit" value="update"></form>
<?php
////////your config db
$qty = $_POST['qty_left'];
if(isset($_POST['submit']);
$sql = mysql_query("insert into issuance_tbl (issued_qty) values (".$qty.") ");
$sql1 = mysql_query("update master_table set qty_left= ".$qty."");
?>
我对“是否有办法做这样的事情”不完全自信:您需要分步进行,就像这样:
$result = $this->db->insert($table);//Example function to insert inventory item
$insert_id = $this->db->insert_id();//Example function to get the id of inserted item
if($result)
$res = $this->db->update($id,$data,$table);//Example function to update data of quantity table
if(!$res)
{
$this->db->delete($insert_id,$table);s
$result = '-1';
}
return $result;
希望这会有所帮助
$con = mysqli_connect($host, $user, $password, $database);
...
$issued_qty = '10'; //some value
$insert_query = "insert into issuance_table (issued_qty, ...) values ('$issued_qty', ... ) ;";
$update_query = "update master_tbl set qty_left = (qty_left - ".$issued_qty.") where ....";
mysqli_multi_query($con, $insert_query.$update_query);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.