如何在mysqli中获取结果/行


How to fetch the result/row in mysqli

我正在学习mysql,但我不确定这段代码中下一步要做什么来获得匹配的行,我该如何获取它?

$stmt= $db->prepare("SELECT * FROM users WHERE email=? and password = ?");
$stmt->bind_param("ss", $_POST['user_name'],md5($_POST['user_pass']));
$stmt->execute();

我相信这对你来说很简单,请帮助我学习。

看看这个页面上的示例#6

这是相关的位,就在bind_param()和execute()之后:

$out_id    = NULL;
$out_label = NULL;
if (!$stmt->bind_result($out_id, $out_label)) {
    echo "Binding output parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
while ($stmt->fetch()) {
    printf("id = %s (%s), label = %s (%s)'n", $out_id, gettype($out_id), $out_label, gettype($out_label));
}

由于我不知道您在SELECT *中插入了哪些列,所以我只保留当前的示例。

您也可以使用fetch_assoc(),它可能更容易使用,并且最终会更常用。从php.net上的同一页面中挖掘,我们从示例#8中得到了这一相关部分(实际上我不得不对其进行一些修改——示例#8在缓冲方面做了一些有趣的事情):

if (!($res = $stmt->get_result())) {
    echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
}
while ($row = $res->fetch_assoc()) {
    var_dump($row);
}
$res->close();