Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem you're probably facing with <code>try...catch</code> is that PHP has two different error handling mechanisms: <a href="http://es2.php.net/manual/en/ref.errorfunc.php" rel="nofollow">error reporting</a> and <a href="http://es2.php.net/manual/en/language.exceptions.php" rel="nofollow">exceptions</a>. You cannot catch exceptions unless the underlying code throws them and good old <code>mysql_query()</code> 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 <a href="http://es.php.net/pdo" rel="nofollow">PDO</a>.</p> <p>In any case, if you want to stick to good old MySQL library, your code should basically work:</p> <pre><code>$res=mysql_query($sql) or die(mysql_error()); </code></pre> <p>The explanation:</p> <ul> <li><code>mysql_query()</code> returns <code>FALSE</code> if the query fails (e.g., you get a duplicate key)</li> <li>The right side of the <code>or</code> expression will only execute if the left side is <code>FALSE</code></li> <li><code>die()</code> aborts the script, thus preventing the next queries to be executed</li> </ul> <p>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:</p> <p> <pre><code>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; } </code></pre> <h1>About transactions</h1> <p>Please note that you still need to use transactions if there's a chance that the <strong>second</strong> query fails. Transactions are not particularly difficult to use, the only requirements are:</p> <ol> <li>Define the involved tables as InnoDB</li> <li>Run a <code>START TRANSACTION</code> query on top of the function</li> <li>Run a <code>COMMIT</code> query at the end of the function</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload