简体   繁体   English

如果 mysql db 表不包含具有特定 ID 的行,则向表中添加数据

[英]If mysql db table does not contain row with specific ID , add data to the table

Hi i'm new to php and mysql.嗨,我是 php 和 mysql 的新手。

I'm wondering how can i use PHP to check if a table in my mysql database contains a ROW which have the specific ID and if not add the data to the table.我想知道如何使用 PHP 检查我的 mysql 数据库中的表是否包含具有特定 ID 的 ROW,如果没有将数据添加到表中。

For example,例如,

Table structure:(Table name: record) ID, DATA表结构:(表名:记录)ID、DATA

i have ID=123 and DATA=hello stored in a variable in the php code, how can i use php sql query to find out whether the data exist by checking using its ID in the table, if not, INSERT the ID and DATA into the table.我有 ID=123 和 DATA=hello 存储在 php 代码中的变量中,我如何使用 php sql 查询来确定数据是否存在,如果不存在,请使用 ID 和 DATA 查询检查数据表桌子。

I hope you understand.我希望你明白。

p/si have connected the php script to the database p/si 已将 php 脚本连接到数据库

Make the ID UNIQUE :使 ID UNIQUE

CREATE TABLE my_table( ID INT UNSIGNED UNIQUE...

then use INSERT IGNORE :然后使用INSERT IGNORE

INSERT IGNORE INTO my_table( ID, DATA ) VALUES( some_id, some_data )
IF NOT EXISTS(SELECT 1 FROM structure WHERE ID = <yourid>)
   INSERT INTO structure (ID, DATA) VALUES(<yourid>, <yourdata>)

Just replace INSERT with REPLACE.只需将 INSERT 替换为 REPLACE。

http://dev.mysql.com/doc/refman/5.5/en/replace.html http://dev.mysql.com/doc/refman/5.5/en/replace.html

Another option:另外的选择:

INSERT INTO record(id, `data`) SELECT 123, 'hello'
FROM new_table WHERE NOT EXISTS (SELECT id from record where id = 123 );

If your ID is unique key, then you can directly try to insert the row.如果你的 ID 是唯一键,那么你可以直接尝试插入行。 If that ID is already in the table, the database would not let you insert it and will return error.如果该 ID 已经在表中,数据库将不允许您插入它并返回错误。 Else you have to first run a SELECT statement to see if this ID exists in your table and if not insert it.否则,您必须首先运行 SELECT 语句以查看此 ID 是否存在于您的表中,如果不存在则插入它。

Also this thread will help you a lot I think How to 'insert if not exists' in MySQL?这个线程也会对你有很大帮助我认为如何在 MySQL 中“插入如果不存在”?

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

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