Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP error level differs from Fatal to warning on same error

Tags:

php

I have some SQL that throws an incorrect syntax message:

$sSQL = "SELECTTTT row from Table";

The first iteration gets caught and produces a Fatal Error

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near 'SELECTTTT'.

The second iteration, produces a warning and subsiquently isn't caught

Warning: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]:

for ($i=0; $i < 2; $i++) { 

    try {

        $st->execute($sSQL);

    } catch (Exception $e) {

        echo $e->GetMessage();
        var_export($e->getTrace()); 

    }

}

can someone please explain what im missing here? Since the command hasnt changed, why is the error produced differing?

like image 327
atoms Avatar asked Aug 22 '26 08:08

atoms


1 Answers

As I said in my initial comment:

This is just a guess, but maybe PDO prepares the query in the background, and kind of remembers it as prepared in the second iteration. And because it's already been prepared it gets run, but that doesn't give the detailed error message

Therefore I believe you need to prepare a new statement handle in every iteration, because your query is different every time.

// connect outside of the loop
$dbh = new PDO($dsn, $user, $pass); 

for ($i=0; $i < 2; $i++) { 

    try {
        // build the query inside of the loop
        $sSQL = "SELECTTTT row from Table"; // this is variable

        // prepare a fresh statement handle for your SQL in every iteration
        $st = $dbh->prepare($sSQL);        

        // run this specific query
        $st->execute();
    } catch (Exception $e) {

        echo $e->GetMessage();
        var_export($e->getTrace()); 

    }
}

Otherwise you're just executing the first query that has already been prepare and passing the value of $sSQL as an argument to execute.

like image 191
simbabque Avatar answered Aug 24 '26 22:08

simbabque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!