I have 2 sql queries to execute, but I want it to execute all or if error in one query then dont execute any. I’m using php. I used to use try and catch in .NET but I’m new to php.
Below is the code which i was trying to do:
function Registration($UserFirstname,$UserLastname){
$sql="INSERT INTO table1 (fieldname1,fieldname2) VALUES ('$UserFirstname','$UserLastname')";
$res=mysql_query($sql) or die(mysql_error());
$sql="INSERT INTO table2 (fieldname1,fieldname2) VALUES ('$UserFirstname','$UserLastname')";
$res=mysql_query($sql) or die(mysql_error());}
The problem you’re probably facing with
try...catchis that PHP has two different error handling mechanisms: error reporting and exceptions. You cannot catch exceptions unless the underlying code throws them and good oldmysql_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:
The explanation:
mysql_query()returnsFALSEif the query fails (e.g., you get a duplicate key)orexpression will only execute if the left side isFALSEdie()aborts the script, thus preventing the next queries to be executedHowever, 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:
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:
START TRANSACTIONquery on top of the functionCOMMITquery at the end of the function