PHP Parse error: syntax error, unexpected token "catch"

Here is my code:

		$sql = "DELETE FROM pwdReset WHERE pwdResetEmail= :userEmail";
        $stmt = $db->prepare($sql);
		$stmt->bindParam(':userEmail', $userEmail, PDO::PARAM_STR);
		return true;

	catch(Exception $e)
        echo 'There was an error: '.$e;
	    return false;
	    header('Location: ../index.php');
echo "666";

And here is thr error message in the error.log file

PHP Parse error: syntax error, unexpected token “catch”
The error appeared when I added echo "666"; between the try and the catch.
When I moved it after the catch closing brace I get a blank page meaning thr code stops after ther try and before the catch
Why is it an error ?
How do I fix it ?

Because this isn’t valid syntax:

try {
  // Whatever
echo "666";
catch (Exception $e) {
  // Whatever

It has to be:

try {
  // Perform some task
} catch (Exception $e) {
  // Jump to this part if an exception occurred

See here:

Also, the sequence of the code inside the catch block is wrong. Once return false; is executed, the following lines won’t run.

1 Like

To be fair, there’s no sequence of those lines in which all of them will run; exit and return are both terminating statements; but even then the echo 666 is STILL in a location that will never be reached; the code either returns true, or it has returned false/exited before it reaches the final echo statement.
Also if you send a header to redirect, you wont see any of the echoes, because the page will redirect.

Ignoring any syntax error you are getting, there is no user recoverable error that can occur for a DELETE query. User recoverable errors are only possible when inserting/updating duplicate or out of range user submitted data values. The only error you can get for this query is due to a programming mistake. Unconditionally outputting the raw database error will only help hackers when they intentionally do things to trigger errors and will just confuse legitimate visitors. You would want to LOG any raw database error from a DELETE query on a live/public server, so that you, the programmer/developer, would know they are occurring and can find and fix them. Therefore, for this query, you should NOT try to catch and handle any exception. Just let php catch and handle the exception, where php will use its error related settings to control what happens with the actual error information, via an uncaught exception error (database statement errors will ‘automatically’ get displayed/logged the same as php errors.)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.