douzoudang1511 2014-07-31 16:05
浏览 25
已采纳

如何在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.

  • 写回答

2条回答 默认 最新

  • dongsetan3216 2014-07-31 16:18
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法