ETAN
ETAN

Reputation: 3182

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/s i have connected the php script to the database

Upvotes: 1

Views: 1415

Answers (5)

Erik A. Brandstadmoen
Erik A. Brandstadmoen

Reputation: 10588

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

Upvotes: 2

Bruno Fl&#225;vio
Bruno Fl&#225;vio

Reputation: 778

Another option:

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

Upvotes: 1

Sean Thayne
Sean Thayne

Reputation: 883

Just replace INSERT with REPLACE.

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

Upvotes: 1

nobody
nobody

Reputation: 10645

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 )

Upvotes: 3

Yasen Zhelev
Yasen Zhelev

Reputation: 4045

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?

Upvotes: 0

Related Questions