Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Record Exists

Tags:

php

I found this on php.net to check if file exists.

I want to check if record exists first, then do update, otherwise do an insert.

if(record exist) {
   update query}
else 
  { insert query}

I know how to update or insert, but don't know how to check if a record exists first. How is it done?

like image 221
user329394 Avatar asked May 17 '10 12:05

user329394


People also ask

How do I check if a record exists in SQL?

The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.

How do you check if data is present in database?

To check whether a particular value exists in the database, you simply have to run just a regular SELECT query, fetch a row and see whether anything has been fetched. Here we are selecting a row matching our criteria, then fetching it and then checking whether anything has been selected or not.


1 Answers

If you know how to do a SQL SELECT, then do that:

$result = mysql_query("SELECT * FROM table1 WHERE something");
$num_rows = mysql_num_rows($result);

if ($num_rows > 0) {
  // do something
}
else {
  // do something else
}

Better yet, don't do this in PHP, use INSERT ... ON DUPLICATE KEY UPDATE.

like image 121
Dominic Rodger Avatar answered Sep 19 '22 00:09

Dominic Rodger