Home >Backend Development >PHP Tutorial >Why Does PDO Return \'SQLSTATE[HY000]\' Instead of Success After an Update Query?
When attempting to update a database using PDO, the error "SQLSTATE[HY000]: General error" can be returned. This error may seem puzzling, as the database is successfully updated despite the reported error.
Cause of the Error
The root cause of this error is the improper use of the fetchAll() method after an update or insert query. PDO's fetchAll() method is typically used to retrieve all rows affected by a select query. However, when executing an update or insert operation, this method is not necessary.
Example of Incorrect Code
The following code attempts to update a database table and retrieve all updated rows using fetchAll():
try { $stmt = $pdo->prepare("UPDATE $page SET $section = :new_content WHERE $section = '$old_content'"); $stmt->execute(array('new_content' => $new_content)); $result = $stmt->fetchAll(); echo "Database updated!"; } catch(PDOException $e) { echo 'ERROR UPDATING CONTENT: ' . $e->getMessage(); }
In this case, the error "SQLSTATE[HY000]: General error" will be thrown because of the use of fetchAll() after the update query.
Correct Solution
To rectify this error, simply remove the fetchAll() statement from the code. The revised code would look like this:
try { $stmt = $pdo->prepare("UPDATE $page SET $section = :new_content WHERE $section = '$old_content'"); $stmt->execute(array('new_content' => $new_content)); echo "Database updated!"; } catch(PDOException $e) { echo 'ERROR UPDATING CONTENT: ' . $e->getMessage(); }
By omitting the fetchAll() statement, the error message "SQLSTATE[HY000]: General error" should disappear, leaving you with a successful database update.
The above is the detailed content of Why Does PDO Return \'SQLSTATE[HY000]\' Instead of Success After an Update Query?. For more information, please follow other related articles on the PHP Chinese website!