我有一张(id, stock_code, batch_code, qty)
的表格。
id
是主键和自动增量值。
stock_code
和batch_code
结合在一起。现在,我希望在stock_code
和batch_code
重复
例如
id stock_code batch_code qty
1 r001 b001 100
2 roo1 b002 100 //it should be insert
3 roo1 boo1 120 //it should be update in first row
4 roo2 boo1 130 //it should be insert
5 roo1 boo2 289 //it should be update in second row
答案 0 :(得分:2)
$stockcode = "some value";
$batchcode="some value";
$qty = some value;
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$query22 = "select * from table where stock_code= '".$stockcode."' and batch_code='".$batchcode."'";
$result22 = mysqli_query($con,$query22) or die (mysqli_error());
$num22 = mysqli_num_rows($con,$result22);
if($num22 > 0) {
$query222 = "update table set qty='".$qty."' where stock_code= '".$stockcode."' and batch_code='".$batchcode."'";
$result222 = mysqli_query($con,$query222) or die (mysqli_error($con));
}
else {
$query222 = "insert into table(stock_code, batch_code, qty) values('".$stockcode."','".$batchcode."','".$qty."') ";
$result222 = mysqli_query($con,$query222) or die (mysqli_error($con));
}
答案 1 :(得分:1)
尝试使用
ON DUPLICATE KEY UPDATE
您可以在此处阅读reff http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
答案 2 :(得分:0)
您正在寻找INSERT ON DUPLICATE KEY UPDATEhttp://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html