0

i'm new to php . i'm just wondering which PHP script can detects if a MySQL database's table contains data . 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.

Thanks and have a nice day .

3 Answers 3

3

You are looking for 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.

Sign up to request clarification or add additional context in comments.

2 Comments

no , i'm not looking for to check whether there's duplicated data , i only want to check if any data exist in a table. If yes , PHP UPDATE the existing data , if not , PHP INSERTS the data
Then just use SELECT id FROM table and check in code if it returns 0 rows, if it doesn't, insert the data.
0

MySQL can help with that depending on your way to check (primary key ?) - see http://www.xaprb.com/blog/2006/02/21/flexible-insert-and-update-in-mysql/

Comments

0

Checking if data exists in a database is a read operation, so you'd use a SELECT statement. If the SELECT statement returns a non-empty recordset, then you know the data exists. Bonus: you also know the id number of the data you're looking for, for use in your update operation.

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.

The only issue with using a SELECT statement is that the operation is not guaranteed to be atomic - that is, this might happen:
- you run the SQL statement and get an empty set
- a different process inserts that form data into the database
- the first process, that ran the select statement, inserts the same form data

Good luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.