PHP - mysqli::prepare returning false

夙愿已清 提交于 2019-12-11 04:32:01

问题


I have this really simple PHP code:

$mysqli = new mysqli('localhost', 'xxx', 'xxxxx', 'xxx');

$query = "SELECT * FROM questions WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('d', $_GET['qid']);
$stmt->execute();
$stmt->bind_result($id, $content, $correct_ans, $lol);
$stmt->fetch();

//do sth with the data

$query = "SELECT * FROM answers WHERE question_id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('d', $_GET['qid']);
$stmt->execute();
$stmt->bind_result($id, $content, $lol);

while($stmt->fetch())
{
    //do sth
}

Basically, it seems that no matter what I do the second mysqli::prepare() will always return false, however mysqli::error is empty for some reason. Can anyone see a mistake here?

PS. It's not a duplicate question; yes, it has been already asked: MySQLi prepared statement returning false but the author didn't bother to share his solution with everybody.

EDIT: I thought I should explain this: ONLY the second prepare returns false, the first is absolutely fine. What is even more weird is that if I remove the first lines of code (ie the first prepare) the second will work without problems...

EDIT2: Well, all I can say now is WTF. It turns out that if I remove the assignment, (I don't do $stmt = prepare()...) but just call the function, $mysqli->error list is not empty - it says "Commands out of sync; you can't run this command now". If I do the assignment, it's empty...

EDIT3: I switched to PDO and it works perfectly. Until I can prove otherwise, I will assume that MySQLi is buggy.


回答1:


Before second usage mysqli::prepare() you must either free mysqli result or close current mysqli statement:

...
//do sth with the data

$mysqli->free(); // or $stmt->close();

$query = "SELECT * FROM answers WHERE question_id = ?";
$stmt  = $mysqli->prepare($query);
...



回答2:


Have you set the correct credentials to database access? username, password....

What do this code returns?

print_r($mysqli->error_list);

http://www.php.net/manual/en/mysqli.error-list.php

SQL query looks OK, but maybe you have wrong database name or table structure...




回答3:


I found that it will silently fail (errno=0, error="") when the return value from prepare is assigned to a variable name which previously held a MYSQLi prepared statement, but will return correct error messages if a new variable is used. The fact that this is even possible says negative things about the PHP execution model IMHO.

Contrary to other answers above, you can have multiple prepared statements and use them concurrently, it's the ancient mysql (not mysqli) driver that cannot walk and chew gum.

I am working in an existing framework, but I heartily recommend switching to PDO which is the canonical way to do it.



来源:https://stackoverflow.com/questions/19466242/php-mysqliprepare-returning-false

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