Reputation: 1496
I am looking at how to update a specific table depending on whether the ID already exists in that table or whether the record needs to be created.
I am planning on using a function which is passed the id number from the main table in the database. The id value.
so something like update($id). But when this function is called I am not quite clear on how to check if the value already exists in the database, if it does then update the record. If it doesn't then create the record. Any thoughts?
I understand how to update the table, but not how to use the conditional statements I require.
$query = "UPDATE reports FROM them where id='$id'";
PSEUDOCODE:
Upvotes: 0
Views: 75
Reputation: 2211
You need to execute a select statement beforehand to check whether a record with that id already exists. If the results from executing the query are not empty, then use an UPDATE statement. If the results are empty, call INSERT instead.
To check for existing records, use the query like the one below. Code sample provided.
SQL:
"Select * from reports where id='$id'";
PHP:
$result = mysql_query("Select * from reports where id='$id'");
if (mysql_num_rows($result) > 0) {
mysql_query("UPDATE...(your update statement query string)");
} else {
mysql_query("INSERT...(your insert statement query string)");
}
Note that this is a basic example, and you should remember to do things like sanitize your query variables to prevent SQL injection, as well as check for error conditions whenever executing a query.
Upvotes: 1