tags:

views:

207

answers:

7

hi all,

i found this to check if file exist. is there a way how to check if record exist first? php.net

i want to check if record exist first, if exist then do update, else do insert. i do understand how to make a queries for select and insert and i dont have problem with it.

if(record exist) {
   update query}
else 
  { insert query}
+1  A: 

Count records matching your criteria?

select count(*) from foo where id = 5

if($count > 0) {
    // record exists
    ...
}
karim79
A: 

You could do a select for that record and inspect the result, or you could try an update and see if there was an error. If there was, then there was nothing to update, so do an insert.

luvieere
+1  A: 

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.

Dominic Rodger
Why the downvote? Did I do something wrong?
Dominic Rodger
+2  A: 

you could also try this

INSERT ... ON DUPLICATE KEY UPDATE
zerkms
+2  A: 

You don't need to do this in PHP, you can do it directly in the SQL query for your database (I'm assuming you're using a database for the records, since that's what it sounds like from your question, and I'll assume MySQL since that's often used along with PHP).

INSERT INTO ... ON DUPLICATE KEY UPDATE;

This would insert a new row if it doesn't already exist, or update the current one if it does, assuming your tables have primary keys.

See the MySQL Manual for more info on this.

The other option is to just do a SELECT COUNT(1) FROM myTable WHERE ... query first, and then only do an insert if the result is 0, otherwise do an update.

Rich Adams
My life became so much easier the day I discovered ON DUPLICATE KEY UPDATE.
Neil Aitken
A: 

You can set the specific columns in your database as primary key and then the insert will success only if you don't have the record already. In this way, you don't event need to check if record exists.

Elad
A: 

I would recommend Dominic Rodger's solution, but with a little change to make it faster. You should select a single value and not more than one row.

$result = mysql_query("SELECT key FROM table1 WHERE something LIMIT 1");
$num_rows = mysql_num_rows($result);

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

If your record already exists, you'll get a result, wich is more than 0 results, so it works, but potentially with less traffic from your SQL-Server.

phogl