对于搜索我正在使用此代码段:
$stmt = $dbh->prepare('SELECT id,username FROM `users` WHERE `username` LIKE :keyword');
$keyword = "%".$data."%";
$stmt->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['user'] = utf8_encode($row['username']);
array_push($return_arr,$row_array);
}
我没有得到那些“LIKE关键字”的值,而是从我的表“users”得到每一个结果,为什么会发生这种情况?
答案 0 :(得分:0)
在准备查询之前,您应该检查$ data是否为空:
if(!empty($data) && is_string($data)){
$stmt = $dbh->prepare('SELECT id,username FROM `users` WHERE `username` LIKE :keyword');
$keyword = "%".$data."%";
$stmt->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['user'] = utf8_encode($row['username']);
array_push($return_arr,$row_array);
}
} else {
// Do something else
}