Here's a great coding tip.
Ever find yourself selecting a row, to see if it exists, just to know whether to insert or update?
$result = mysql_query("select id from table where id = 123");
if(mysql_num_rows($result)){
mysql_query("update table set name = 'foo' WHERE id = 123");
}else{
mysql_query("insert into table (id,name) values (123,'foo')");
}
try this, instead.
mysql_query("update table set name = 'foo' WHERE id = 123");
if(!mysql_affected_rows()){
mysql_query("insert into table (id,name) values (123,'foo')");
}
mysql_affected_rows() returns the number of rows that were changed by the previous query.
So if no rows were updated in the UPDATE, then you know the id 123 doesn't exist. The zero returned evaluates to false, and you insert the row.
It saves one redundant SELECT, and only does the INSERT if the UPDATE does nothing. It's easier to code, looks more elegant, and runs faster too.