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?
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With