PDO: Using fetchAll, still receiving General error

2019-09-19 15:42发布

问题:

This problem is proceeding to drive me crazy...

First a disclaimer, I have very little formal programming training. I am stumbling thru this.

I am receiving the General error: 2014 error; at first it was one particular query (which was established in a class) and the warning was dependent upon where in the code I was instantiating the object. I proceeded to change every query to a fetchAll and then closed the cursor for every query as well after the fetchAll didn't work. Now there are two offending queries. Here is a copy and paste of one:

(UPDATED CODE):

$sql = "select initial_state from source_nodes where id = :id";

$core = Core::getInstance();
$stmt = $core->dbh->prepare($sql);
$stmt->bindParam(':id', $allSources->id[$id], PDO::PARAM_INT);

if ($stmt->execute()) {
    $row = $stmt->fetchAll();
    $stmt->closeCursor();
    foreach($row as $i=>$value){
        $allSources->state[$id] = $row[$i]['initial_state'];
    }
}

Not certain if it matters, but the warning is thrown on the 'if'. As far as I am aware, every 'fetch' is now a 'fetchAll' and includes a 'closeCursor'.

The connection is being set like this:

$this->dbh = new PDO($dsn, $user, $password, array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_USE_BUFFERED_QUERY =>true
            ));

Suggestions?

回答1:

$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE);

is the silver bullet to fix the error, which text you didn't even bothered to provide, supposing readers to know every error by numbers by heart.

While just mechanically replacing all the fetch() calls to fetchAll() is not.

Two things on your edited code.

  1. You have quite useless loop. As I said above, doing something mechanically, mindlessly, can bring no good. One have to have at least minimal understanding. The loop you have is useless twice: because $row you have from fetchAll() don't need any looping over (it already contain all the data) and because you are getting only one row anyway and no loop ever needed. And thus fetch() should be used not fetchAll.
  2. Despite of your feeling, not "every 'fetch' is now a 'fetchAll'" as the error message clearly tells us.
  3. It seems you are selecting rows one by one inside of a larger loop. And it apparently smells of some wrong query. You have to make this (invisible to us) outer query to get all the data at once, using fetchAll() and without all these inner queries.


回答2:

I think that it could be a PHP bug.

https://bugs.php.net/bug.php?id=57540

What is your PHP version?



标签: php pdo fetchall