简体   繁体   中英

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

Hi i'm new to php and 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.

For example,

Table structure:(Table name: record) 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.

I hope you understand.

p/si have connected the php script to the database

Make the ID UNIQUE :

CREATE TABLE my_table( ID INT UNSIGNED UNIQUE...

then use 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.

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. If that ID is already in the table, the database would not let you insert it and will return error. Else you have to first run a SELECT statement to see if this ID exists in your table and if not insert it.

Also this thread will help you a lot I think How to 'insert if not exists' in MySQL?

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