PDO Error - PDOException' with message 'SQLSTATE[HY000]: General error' [duplicate]

核能气质少年 提交于 2020-01-19 11:13:07

问题


I am getting this error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error' in ...

..whenever I execute this code with PDO:

//Select data from the topic.
$s = $dbh->prepare("SELECT * FROM forum_topics WHERE forum_id=:forum_cat_id AND topic_id=:topicid");
$s->bindParam(':forum_cat_id', $forum_cat_id);
$s->bindParam(':topicid', $topicid);
$s->execute();
$f = $s->fetch();

$s = $dbh->prepare("UPDATE forum_cats 
    SET 
        forum_last_postid = :last_post_id, forum_last_posttime = :time, 
        forum_last_userid = :userid, forum_last_username = :username, 
        forum_posts=forum_posts+1 
    WHERE forum_id = :forum_cat_id");
$s->bindParam(':last_post_id', $last_post_id);
$s->bindParam(':time', $time);
$s->bindParam(':userid', $userid);
$s->bindParam(':username', $userdata['username']);
$s->bindParam(':forum_cat_id', $forum_cat_id);
try {
    $s->execute();
}
catch(PDOException $e) {
    die($e->getMessage());
}

if (count($s->fetchAll()) == 0) {
    return 3;
}

I have no idea why this is happening. I've checked the query, and I simply cant find any errors..


回答1:


This is what happens:

  • You are trying to fetch an UPDATE query. You can't do that because UPDATE queries does not return values. If you wish to know how many rows were affected by the query, use the rowCount() function instead. Notice that not all DB Drivers provide the affected rows.

  • You are using undeclared variables (at least in the code you posted here). This isn't the reason for this particular error, but could generate others.

  • You're not using the data you have selected from the database

    Also, it is recommended to make all PDO operations within the try block, otherwise you may get unhandled exceptions.




回答2:


For others who came here trying to decipher this esoteric error message as I did, let me add that:

Trying to run fetches on pdo statements like:

$statement->fetchAll();

or

$statement->fetchAll(PDO::FETCH_ASSOC);

...after an INSERT or UPDATE** statement can cause this error (since there is no data to fetch).

**The UPDATE ... RETURNING ... statement is an exception to this.



来源:https://stackoverflow.com/questions/20315898/pdo-error-pdoexception-with-message-sqlstatehy000-general-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!