我如何使用mysqli用LIKE进行查询并获得所有结果?
这是我的代码,但是不起作用:
$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行,我如何获得所有结果呢?
这是您正确获取结果的方式
$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_array(MYSQLI_NUM)) { foreach ($row as $r) { print "$r "; } print "\n"; }