![](/img/trans.png)
[英]If Record exists UPDATE MySql Table or else INSERT using PHP
[英]If record exists then update or else Insert in php/mysql
实际情况是。 我的数据库中有一些记录。 我以编辑模式调用记录。 在此模式下,用户可以“添加更多行”(动态行),并且可以更新。 因此,应该更新存在的记录,并将新添加的行插入到表中。
我正在尝试执行一个查询,该查询会更新“ ID”是否存在,如果不存在则插入。 这里我使用“ ON DUPLICATE KEY UPDATE”。 当我尝试运行以下查询时,我可以看到插入了很多重复的记录。 我猜由于WHILE LOOP而产生了重复的记录。 。 我的查询如下。 Id是“自动递增”和“键”。 我没有收到任何查询错误。 DB是Mysql。 我的php保存脚本如下:还检查前端。.https ://jsfiddle.net/euvof3xb/14/
while ($i < $size) {
$sl= $_POST['sl'][$i];
$item_id= $_POST['item_id'][$i];
$item_name= $_POST['item_name'][$i];
$prod_description=$_POST['prod_description'][$i];
$prod_description= mysql_real_escape_string($prod_description);
$item_quantity= $_POST['item_quantity'][$i];
$item_units= $_POST['item_units'][$i];
$unitprice= $_POST['unitprice'][$i];
$total=$_POST['total'][$i];
$currency_selected=$_POST['currency_change'][$i];
$total_inr= $_POST['total_inr'][$i];
$id = $_POST['id'][$i];
$item_quantity_sup= $_POST['item_quantity_sup'][$i];
$slab_range= $_POST['slab_range'][$i];
$item_units_sup= $_POST['item_units_sup'][$i];
$item_partno= $_POST['item_partno'][$i];
$ifmain= $_POST['ifmain'][$i];
$sup_itempartno = $_POST['sup_itempartno'][$i];
$query = "INSERT INTO comparitive_st_sup (
id,
tender_id,
item_id,
ifmain,
slno,
item_name,
item_partno,
prod_description,
sup_itempartno,
currency,
slab_range,
qty,
total_inr,
qty_sup,
item_units,
item_units_sup,
unitprice,
total,
supplier_name
)
VALUES (
$id,
'$tender_id',
'$item_id',
'$ifmain',
'$sl',
'$item_name',
'$item_partno',
'$prod_description',
'$sup_itempartno',
'$currency_selected',
'$slab_range',
'$item_quantity',
'$total_inr',
'$item_quantity_sup',
'$item_units',
'$item_units_sup',
'$unitprice',
'$total',
'$supplier_name2'
)
ON DUPLICATE KEY UPDATE
ifmain='$ifmain',
slno = '$sl',
item_name = '$item_name',
item_partno = '$item_partno',
prod_description = '$prod_description',
sup_itempartno = '$sup_itempartno',
currency = '$currency_selected',
slab_range= '$slab_range',
qty = '$item_quantity',
qty_sup = '$item_quantity_sup',
item_units = '$item_units',
item_units_sup = '$item_units_sup',
unitprice = '$unitprice',
total = '$total',
total_inr='$total_inr'";
mysql_query($query) or die ("Error in query: $query");
++$i;
}
一种最简单的解决方法是,您要将数据库中的“ id”字段设为主键。 这样可以自动避免重复输入。
其次,
您可以尝试以下代码在插入和更新之间进行切换,
$count=mysql_numrows(mysql_query("SELECT * FROM comparitive_st_sup WHERE id=$id"));
if($count)
{
$query={UpdateQuery}
}
else
{
$query={InsertQuery}
}
另外,不建议使用mysql函数。 因此,请开始使用mysqli函数进行编程。
希望这会有所帮助。 谢谢。
我通过首先删除完整的行并再次插入来解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.