准备好的语句获取行不返回任何内容

时间:2017-09-14 17:50:50

标签: php mysql prepared-statement fetch

我想获取此行并将其保存到$notescheck,但是当我尝试执行此操作时,$notescheck在我想要回显并且没有错误时为空。对于未准备好的陈述,它可以正常工作。

代码:

if($user_ok == true) {
    $sql = "SELECT notescheck FROM users WHERE username=? LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s",$log_username);
    $stmt->execute();
    $row = $stmt->fetch();
    $notescheck = $row[0];
    $stmt->close();
}

对于未准备好的陈述,它看起来像这样:

 if($user_ok == true) {
    $sql = "SELECT notescheck FROM users WHERE username='$log_username' LIMIT 1";
    $query = mysqli_query($conn, $sql);
    $row = mysqli_fetch_row($query);
    $notescheck = $row[0];
    mysqli_close($conn);
}

1 个答案:

答案 0 :(得分:1)

这不是fetch()如何使用预处理语句,你不是像你认为的那样获取数组。您还需要将select的结果绑定到变量中,然后使用它们进行显示。如果有多条记录,则使用while($stmt->fetch){ echo $notescheck };

if($user_ok == true) {
    $sql = "SELECT notescheck FROM users WHERE username=? LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s",$log_username);
    $stmt->execute();
    $stmt->bind_result($notescheck);
    $stmt->fetch();
    $stmt->close();
}
echo $notescheck;

你应该检查一下:

http://php.net/manual/en/mysqli-stmt.fetch.php

匹配username = x的多条记录如下所示:

if($user_ok == true) {
        $sql = "SELECT notescheck FROM users WHERE username=? LIMIT 1";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s",$log_username);
        $stmt->execute();
        $stmt->bind_result($notescheck);
        $stmt->store_result()
        while($stmt->fetch()){
           echo $notescheck;
        }
        $stmt->close();
    }