PDO 错误 - PDOException' 带有消息 'SQLSTATE[HY000]: 一般错误'

2021-12-26 00:00:00 php mysql pdo

我收到此错误:

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

...每当我使用 PDO 执行此代码时:

..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..

推荐答案

事情是这样的:

  • 您正在尝试获取 UPDATE 查询.您不能这样做,因为 UPDATE 查询不返回值.如果您想知道查询影响了多少行,请改用 rowCount() 函数.请注意,并非所有数据库驱动程序都提供受影响的行.

  • 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

另外,建议在try块内进行所有PDO操作,否则可能会得到未处理的异常.

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

相关文章