简体   繁体   English

如果mysql表包含data,请更新它,如果不插入数据(PHP)

[英]If mysql table contains data , update it , if not insert the data (PHP)

i'm new to php . 我是php新手。 i'm just wondering which PHP script can detects if a MySQL database's table contains data . 我只是想知道哪个PHP脚本可以检测MySQL数据库表是否包含数据。 If yes , it will update the data with the submitted form data. 如果是,它将使用提交的表单数据更新数据。 If not(blank) it will insert the form data into it. 如果不是(空白),它将在其中插入表格数据。

I know how to insert data using php just wondering how can i CHECK if data exist in a table. 我知道如何使用php插入数据,只是想知道如何检查表中是否存在数据。

Thanks and have a nice day . 感谢,并有一个愉快的一天 。

You are looking for INSERT ... ON DUPLICATE KEY UPDATE . 您正在寻找INSERT ... ON DUPLICATE KEY UPDATE

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

Just append the ON DUPLICATE KEY UPDATE x=y, z=a to your current INSERT and if the unique value you try to insert already exists, the row containing it is updated. 只需将ON DUPLICATE KEY UPDATE x=y, z=a附加到当前的INSERT ,如果您尝试插入的唯一值已经存在,则包含该值的行将被更新。

MySQL可以根据您的检查方式(主键?)提供帮助-参见http://www.xaprb.com/blog/2006/02/21/flexible-insert-and-update-in-mysql/

Checking if data exists in a database is a read operation, so you'd use a SELECT statement. 检查数据库中是否存在数据是一项读取操作,因此您将使用SELECT语句。 If the SELECT statement returns a non-empty recordset, then you know the data exists. 如果SELECT语句返回一个非空记录集,那么您就知道该数据存在。 Bonus: you also know the id number of the data you're looking for, for use in your update operation. 奖励:您还知道要查找的数据的ID号,以用于更新操作。

The INSERT... ON DUPLICATE KEY UPDATE is great if you know the unique id number of the row you're updating... which you might now. 如果您知道要更新的行的唯一ID号,则INSERT ... ON DUPLICATE KEY UPDATE非常有用。

The only issue with using a SELECT statement is that the operation is not guaranteed to be atomic - that is, this might happen: 使用SELECT语句的唯一问题是不能保证该操作是原子的-也就是说,这可能会发生:
- you run the SQL statement and get an empty set -您运行SQL语句并获得一个空集
- a different process inserts that form data into the database -不同的过程将形成数据的形式插入数据库
- the first process, that ran the select statement, inserts the same form data -运行select语句的第一个过程将插入相同的表单数据

Good luck! 祝好运!

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

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