简体   繁体   English

更新mysql php中的特定字段

[英]UPDATE specific fields in mysql php

I've a table in MySQL named product where fields are set as below.. 我在MySQL中有一个名为product的表,其中字段设置如下。

id int(3) NOT NULL AUTO_INCREMENT,
nm varchar(255),
category varchar(255),
price int(4)

when i insert a new product then I've put some code to check duplication as below. 当我插入一个新产品,然后我已经放了一些代码来检查重复,如下所示。

select nm,category from product where nm='".$pnm."' AND category='".$cat."'

If there is any row then code will not insert that record in database...(problem starts now) same condition I've set during update.. if user edit that product and change name or category which is already in database then it'll return false and exit the code.. 如果有任何行,那么代码将不会在数据库中插入该记录...(问题现在开始)我在更新期间设置的相同条件..如果用户编辑该产品并更改已存在于数据库中的名称或类别那么它' ll返回false并退出代码..

now if i want to just update price then name and category will be same then what to do??? 现在,如果我只想更新价格,那么名称和类别将是相同的然后做什么???

please give your best ! 请尽力! ! Thank you friends 谢谢各位朋友

You can do it by using unique id..First check for duplication while updating and if duplication occurs then only update other fields except name and category else update all the fields which are going to be changed. 您可以使用唯一ID来执行此操作。在更新时首先检查重复,如果发生重复,则只更新除名称和类别之外的其他字段,否则更新将要更改的所有字段。

I give you demo.Make changes according to your requirement like field name,table name and all that. 我给你demo.Make根据你的要求进行更改,比如字段名称,表名和所有这些。

$sql="select * from product where nm='".$_REQUEST['name']."'" or category='".$_REQUEST['category']."';
$query=mysql_query($sql);
if(mysql_num_rows($query)>0)
{
 while($row=mysql_fetch_array($query))
 {
   $id=$row['id'];
   if(isset($_REQUEST['price']))
   {
    $sql="update product set price='".$_REQUEST['price']."' where id='$id'";
    $query=mysql_query($sql);
   }
 }
}
else
{
$sql="update product set nm='".$_REQUEST['name']."',category='".$_REQUEST['category']."',price='".$_REQUEST['price']."' where id='$id'";
$query=mysql_query($sql);
}

两步解决方案: - 创建UNIQUE索引 - 使用INSERT IGNOREUPDATE IGNORE而不是INSERTUPDATE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM