简体   繁体   中英

How to update row in PHP/mysql?

I import outlook contacts file into my database and then display it into html table. The table is created and everything is ok, but when I try to upload it a second time, all names and information is doubled. So what I want to do is if the first name and the last name already exists just to update the row and all cells in that row and not insert that row over and over again.

"CREATE TABLE contacts(PID INT NOT NULL AUTO_INCREMENT,PRIMARY KEY(PID),first_name CHAR(80),middle_name CHAR(80),last_name CHAR(80)"

I tried with on duplicate key update/replace but it didnt work.

"INSERT INTO contacts (first_name,middle_name,last_name)
VALUES ('$first_name','$middle_name','$last_name')"

I guess my problem is in the auto_increment and primary key but I don't really understand how they work and how to do that.

Your INSERT would never "update" your existing record, because you're missing the "on duplicate key" business:

INSERT INTO sometable (field1, field2) 
ON DUPLICATE KEY UDPATE field1=VALUES(field1), field2=VALUES(field2)

and of course, this will only work if the INSERT would actually cause a duplicate key violation. The only unique index you have in your table is the primary key, and you're not inserting a value into it at all, so there will NEVER be a duplicate key violation.

You probably want an UPDATE query instead:

UPDATE yourtable
SET field1='value for field1', field2='value for field2'
WHERE id=$your_record_id

you could add an hidden field with PID in the HTML, and when you upload to mySQL, you can add a stored procedure to check if it exist or not. If it exists, update if not, insert.

*In case of new user, the PID in the hidden field could be = -1

might want to look at this : Check if record exists, if yes "update" if not "insert"

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