MySQLi无法准备语句 [英] MySQLi failing to prepare a statement

查看:80
本文介绍了MySQLi无法准备语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在脚本room.php中运行两个查询.两者都使用MySQLi预准备语句,其代码如下:

I'm running two queries in my script room.php. Both are using MySQLi prepared statements, and their code are as follows:

/* Get room name */
$stmt = $mysqli->prepare('SELECT name FROM `rooms` WHERE r_id=?');
$stmt->bind_param('i', $roomID);
$stmt->execute();
$stmt->bind_result($roomName)

/* Add this user to the room */
$stmt = $mysqli->prepare('INSERT INTO `room_users` (r_id, u_id) VALUES (?, ?)');
$stmt->bind_param('ii', $roomID, $_SESSION['userID']);
$stmt->execute();

运行脚本时,出现此错误:

When I run the script, I get this error:

Fatal error: Call to a member function bind_param() on a non-object in C:\wamp\www\room.php on line 24

哪个是第二个查询.如果我从脚本中删除第一个查询,则一切运行正常.同样,如果我删除第二个查询.这使我相信存在问题,因为我正在重用$stmt对象.如果我尝试使用$stmt2进行第二次查询,我仍然会收到错误消息.

Which is the second query. If I remove the first query from the script, everything runs fine. Likewise if I remove the second query. Which leads me to believe there's a problem because I'm reusing the $stmt object. If I try the second query using $stmt2 I still get the error.

我所有的数据库表和字段都存在,因此查询没有问题.

All my database tables and fields exist, so there's nothing wrong with the queries.

推荐答案

所有mysqli函数/方法都可能失败,在这种情况下,它们将返回false. IE.如果prepare()失败$ stmt不是对象,则可以调用bool(false)上的方法.您必须检查返回值并添加一些错误处理,例如

All of the mysqli functions/methods can fail in which case they will return false. I.e. if prepare() fails $stmt isn't an object you can call a method on but a bool(false). You have to check the return values and add some error handling, e.g.

$stmt = $mysqli->prepare('SELECT name FROM `rooms` WHERE r_id=?');
if ( !$stmt ) {
    printf('errno: %d, error: %s', $mysqli->errno, $mysqli->error);
    die;
}

$b = $stmt->bind_param('i', $roomID);
if ( !$b ) {
    printf('errno: %d, error: %s', $stmt->errno, $stmt->error);
}

$b = $stmt->execute();
if ( !$b ) {
  and so on and on

请参见 http://docs.php.net/mysqli-stmt.errno

在这种情况下,您可能会遇到一个问题,即,在前一条语句仍然有待处理的结果/结果集的情况下,您无法创建其他语句.
参见 http://docs.php.net/mysqli-stmt.close :

in this case you probably bumped into the problem that you can't create an other statement while there are still results/result sets pending for the previous statement.
see http://docs.php.net/mysqli-stmt.close:

关闭准备好的语句. mysqli_stmt_close()也取消分配语句句柄.如果当前语句具有待处理或未读的结果,则此函数将其取消,以便可以执行下一个查询.
Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

这篇关于MySQLi无法准备语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆