【发布时间】:2012-09-13 19:26:04
【问题描述】:
这是我的问题...我正在尝试返回多行而不使用“LIKE”子句从我的 PDO 语句中刷新页面,问题是它只返回一行而不是其余的...有人可以吗请帮我?提前致谢
这是我的 html 表单:
<h2>Please insert the username you would like to search for</h2>
<div align="center" id="loader_div"><span id="search_result"></span></div>
<form action="send/search.php" method="post" id="search_form">
<input type="text" id="search_username" name="get_name" />
<input type="submit" name="submitsearch" />
</form>
<div id="get_users">
</div>
我的PHP如下:
$search = $_POST['get_name'];
$query = $db->prepare("SELECT *
FROM `users`
WHERE `users`.`username` LIKE ? LIMIT 10");
$query->bindValue(1, "%".$search."%", PDO::PARAM_STR);
try {
$query->execute();
$data['success'] = true;
while($row = $query->fetch(PDO::FETCH_OBJ)) {
$data['users'] = " ".$row->username." ";
echo json_encode($data);
exit();
}
} catch (PDOException $e) {
die($e->getMessage());
exit();
}
这是我返回 PHP 结果的 jQuery:
$.ajax ({
type: "POST",
url: "send/search.php",
data: $('#search_form').serialize(),
dataType: "json",
success: function(data){
if(data.success === true)
{
$("#display_users").html(data.users);
},
error: function(xhr, status, et) {
}
});
【问题讨论】:
-
注意,您不能只是将 JSON 连接在一起并使其有效。例如,
{"a":"b"}{"a":"c"}无效。将结果收集到一个数组中并对其进行编码,它应该会更好地工作。至于为什么只有一行……你知道exit()是做什么的,对吧?
标签: php pdo while-loop json