The problem you're probably facing with try...catch
is that PHP has two different error handling mechanisms: error reporting and exceptions. You cannot catch exceptions unless the underlying code throws them and good old mysql_query()
will trigger warnings rather than throwing exceptions. There're several workarounds but, if you are interested in writing good object-oriented code, I suggest you switch to PDO.
In any case, if you want to stick to good old MySQL library, your code should basically work:
$res=mysql_query($sql) or die(mysql_error());
The explanation:
mysql_query()
returns FALSE
if the query fails (e.g., you get a duplicate key)
- The right side of the
or
expression will only execute if the left side is FALSE
die()
aborts the script, thus preventing the next queries to be executed
However, I presume that you don't want to abort in the middle of nowhere. If we add some missing bits (such as proper SQL generation and code indentation) we get this:
function Registration($UserFirstname,$UserLastname){
$sql = sprintf("INSERT INTO table1 (fieldname1,fieldname2) VALUES ('%s','%s')";
mysql_real_escape_string($UserFirstname),
mysql_real_escape_string($UserLastname)
);
$res = mysql_query($sql);
if( !$res ){
return FALSE;
}
$sql = sprintf("INSERT INTO table2 (fieldname1,fieldname2) VALUES ('%s','%s')";
mysql_real_escape_string($UserFirstname),
mysql_real_escape_string($UserLastname)
);
$res = mysql_query($sql);
if( !$res ){
return FALSE;
}
return TRUE;
}
About transactions
Please note that you still need to use transactions if there's a chance that the second query fails. Transactions are not particularly difficult to use, the only requirements are:
- Define the involved tables as InnoDB
- Run a
START TRANSACTION
query on top of the function
- Run a
COMMIT
query at the end of the function