简体   繁体   中英

UPDATE specific fields in mysql php

I've a table in MySQL named product where fields are set as below..

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..

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.

I give you demo.Make changes according to your requirement like field name,table name and all that.

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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