如何使用 mysqli 使用 LIKE 进行查询并获得所有结果? [英] How can I with mysqli make a query with LIKE and get all results?

查看:33
本文介绍了如何使用 mysqli 使用 LIKE 进行查询并获得所有结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,但它不起作用:

This is my code but it dosn't work:

$param = "%{$_POST['user']}%";
$stmt = $db->prepare("SELECT id,Username FROM users WHERE Username LIKE ?");
$stmt->bind_param("s", $param);
$stmt->execute();
$stmt->bind_result($id,$username);
$stmt->fetch();

这段代码似乎不起作用.我已经搜索了很多.它也可能返回超过 1 行.那么即使返回超过 1 行,我如何获得所有结果?

This code it doesn't seem to work. I have searched it a lot. Also it may return more than 1 row. So how can I get all the results even if it returns more than 1 row?

推荐答案

这是正确获取结果的方法

Here's how you properly fetch the result

$param = "%{$_POST['user']}%";
$stmt = $db->prepare("SELECT id,username FROM users WHERE username LIKE ?");
$stmt->bind_param("s", $param);
$stmt->execute();
$stmt->bind_result($id,$username);

while ($stmt->fetch()) {
  echo "Id: {$id}, Username: {$username}";
}

或者你也可以这样做:

$param = "%{$_POST['user']}%";
$stmt = $db->prepare("SELECT id, username FROM users WHERE username LIKE ?");
$stmt->bind_param("s", $param);
$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo "Id: {$row['id']}, Username: {$row['username']}";
}

我希望你意识到我直接从手册中得到了答案这里这里,这是您应该先走了.

I hope you realise I got the answer directly from the manual here and here, which is where you should've gone first.

这篇关于如何使用 mysqli 使用 LIKE 进行查询并获得所有结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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