简体   繁体   English

如何在PHP / mysql中更新行?

[英]How to update row in PHP/mysql?

I import outlook contacts file into my database and then display it into html table. 我将Outlook联系人文件导入数据库,然后将其显示到html表中。 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. 我猜我的问题出在auto_increment和主键上,但是我不太了解它们如何工作以及如何做到这一点。

Your INSERT would never "update" your existing record, because you're missing the "on duplicate key" business: INSERT将永远不会“更新”现有记录,因为您缺少“重复键”业务:

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. 当然,这仅在INSERT实际上导致重复键冲突的情况下才有效。 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查询:

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. 您可以在HTML中添加带有PID的隐藏字段,并且当您上传到mySQL时,可以添加存储过程来检查它是否存在。 If it exists, update if not, insert. 如果存在,则更新,如果不存在,则插入。

*In case of new user, the PID in the hidden field could be = -1 *如果是新用户,则隐藏字段中的PID可能= -1

might want to look at this : Check if record exists, if yes "update" if not "insert" 可能要看一下: 检查记录是否存在,如果是,则更新,如果不是,则“插入”

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

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