简体   繁体   English

Mysqli Prepare在另一个准备好的语句中不起作用

[英]Mysqli Prepare is not working inside another prepared statement

I am trying to run a prepared statement inside a prepared statement but got no success. 我试图在一个准备好的语句中运行一个准备好的语句,但是没有成功。 Here is my code: 这是我的代码:

if ($stmt = $mysqli->prepare("SELECT author_id FROM posts")) {
$stmt->execute();
$stmt->bind_result($author_id);
    while ($stmt->fetch()) {
        if ($stmt2 = $mysqli->prepare("SELECT username FROM users WHERE id=? LIMIT 1")) {
            $stmt2->bind_param("s", $author_id);
            $stmt2->execute();
            $stmt2->bind_result($username);
            $stmt2->fetch();
            $stmt2->close();

            //showing username
            echo $username;
        }
    }
    $stmt->close();
}

I am getting author id from a table and then from author id I'm trying to get author's name from another table. 我从一个表中获取author id ,然后从author id中获取另一个表中的作者姓名。
Can you please tell me any way to do this or any modification in this script can get it done. 您能告诉我执行此操作的任何方法吗,或者对该脚本进行任何修改都可以完成此操作。

Sometimes PHP section of this site makes my eyes aching. 有时,该站点的PHP部分使我感到疼痛。 Not only question lacks very basic knowledge in every aspect of programming, but also answers promote terrible practices. 问题不仅在编程的各个方面都缺乏非常基础的知识,而且答案也促进了糟糕的实践。

  1. You have to report errors to make yourself aware of the certain reason. 您必须报告错误以使自己知道某些原因。 Either usual way, via $conn->error or by setting mysqli in exception mode. 通过$conn->error或通过将mysqli设置为异常模式的通常方法。
  2. After reading the error message, you can google for a solution - store_result() 阅读错误消息后,您可以通过Google搜索解决方案store_result()
  3. For such a dataset, NO loop needed ever, as you have to use JOIN instead: 对于这样的数据集,永远不需要NO循环,因为您必须使用JOIN来代替:

And so whole code become 这样整个代码就变成了

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$sql = "SELECT username FROM posts p, users u WHERE u.id=author_id";
$res = $mysqli->query($sql);
while ($row = mysqli_fetch_row()) {
    echo $row[0];
}

Use another mysqli object for inner loop. 使用另一个mysqli对象进行内部循环。

$mysqli = new mysqli(host, user, password, dbname);
$mysqli2 = new mysqli(host, user, password, dbname);

if ($stmt = $mysqli->prepare("SELECT author_id FROM posts")) {
$stmt->execute();
$stmt->bind_result($author_id);
while ($stmt->fetch()) {
    if ($stmt2 = $mysqli2->prepare("SELECT username FROM users WHERE id=? LIMIT 1")) {
        $stmt2->bind_param("s", $author_id);
        $stmt2->execute();
        $stmt2->bind_result($username);
        $stmt2->fetch();
        $stmt2->close();

        //showing username
        echo $username;
    }
}
$stmt->close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM