Click to See Complete Forum and Search --> : insert or update


farruinn
10-06-2007, 07:07 PM
Hi, I'm fairly green when it comes to SQL. I'm writing a scheduling program for the camp I run using PHP and mySQL 5.

I have a form for registering a participant in sessions. I would like the same form to make new entries in the database if they haven't been registered for anything yet and to replace sessions if they have been registered for other sessions already.

My question is, is there a single SQL statement I can use for this or should my PHP script determine if an insert or update command is needed?

scragar
10-06-2007, 07:32 PM
you could try an update, test mysql_affected_rows() and insert if not in:

<?php
mysql_query("UPDATE ");
if(mysql_affected_rows()){
mysql_query("INSERT");
echo "inserted.";
}else
echo "updated.";
?>

NightShift58
10-07-2007, 01:20 PM
Use REPLACE if you have an index that is unique. It will then automatically either INSERT or DELETE & INSERT for you.

An alternative, which also requires at least one unique index, is INSERT...ON DUPLICATE KEY...

farruinn
10-07-2007, 06:31 PM
Thanks, replace is exactly what I was looking for.