Alaey
Alaey

Reputation: 41

Parse error: syntax error, unexpected 'catch' (T_CATCH)

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);
    }
} 

Upvotes: 1

Views: 2896

Answers (2)

Jerodev
Jerodev

Reputation: 33196

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.

Upvotes: 7

maesbn
maesbn

Reputation: 207

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

Upvotes: -3

Related Questions