Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop on a mysql call is throwing unknown PDO exception 'General Error'

Tags:

php

while-loop

I use the following (or similar) code on hundreds of pages I have built:

$stmt = $db->prepare("SELECT * FROM table");
$stmt->execute();

while($row = $stmt->fetch()) {

    $id = $row['id'];
    $name = $row['name'];

    do something with data returned...


    $id = NULL;
    $name = NULL;

}

Out of nowwhere, I started receiving the following error on a few pages:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error' in C:....page.php:28 Stack trace: #0 C:..page.php(28): PDOStatement->fetch() #1 {main} thrown

The first loop will run (with no problem) but gives an error AFTER the first loop. The error code (line 28) references the line:

while($row = $stmt->fetch()) {

I have never seen this before. As a test, I modified the code to store all returned results as:

$stmt = $db->prepare("SELECT * FROM table");
$stmt->execute();

$rows = $stmt->fetchALL();

foreach($rows as $row) {

    $id = $row['id'];
    $name = $row['name'];

    do something with data returned...


    $id = NULL;
    $name = NULL;

}

and the system works. Any idea as to why?

like image 720
JM4 Avatar asked Jun 06 '26 03:06

JM4


2 Answers

Note: After looking through 'do something' area again - I realized the database initializers ($sql) were the same in the select and an insert/update statement within the body. Changing these to unique values corrected the issue.

Thanks

like image 136
JM4 Avatar answered Jun 07 '26 18:06

JM4


Unless this is merely a typo in your question, your arrow operator is incomplete.

$stmt>execute();

// Should be
$stmt->execute();
like image 37
Michael Berkowski Avatar answered Jun 07 '26 16:06

Michael Berkowski