1

Why is this code causing a syntax error? Why can't I catch the exception?

protected function RunQuery($sql) {
    $pdo = $this->conn;
    $stmt = $pdo->prepare($sql);

    if($stmt) {
        $stmt->execute($sql);
    } else {
        print_r("Unable to prepare the query");
    }
    catch(PDOException $e) {
        print_r($e);
        exit(0);
    }
} 
2
  • 1
    Just as the error states, you have an unexpected catch statement. Why is that statement there? Commented Feb 14, 2017 at 15:53
  • 2
    catch always works with try, with the syntax try{ /*code*/ }catch(Exception $e){ /*code*/ }. see php.net/manual/fr/language.exceptions.php Commented Feb 14, 2017 at 15:55

2 Answers 2

7

You need to have a try block before you can add a catch block. You will need to change your code to something like this:

protected function RunQuery ($sql) { 

    $pdo = $this->conn;

    try
    {
        $stmt = $pdo->prepare($sql);

        if ($stmt) {
            $stmt->execute($sql);
        } else {
            print_r("Unable to prepare the query");
        }
    }
    catch (PDOException $e) {
        print_r($e);
        exit(0);
    }
} 

More information about try & catch and how to work with exceptions can be found in the php documentation.

Sign up to request clarification or add additional context in comments.

Comments

-3

Seems like you are missing an '}' on the line above catch.

2 Comments

Moving the catch statement outside the function would also be "unexpected" to the parser.
the catch is inside the function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.