[英]How to limit results retrurned by MySQL query?
I have this piece of code and it works great. 我有这段代码,效果很好。 The only issue is that I will get multiple results at once and I just need the one. 唯一的问题是,我将一次获得多个结果,而我只需要一个。 Lets say I am looking for account # 2, if I type two into the input box name="id" , I will get all results that have the number 2.. If I want to look for a specific person's name, and I type first name and then I enter another last name.. it will bring the first name I want but it will bring other results with the last name I entered. 假设我正在寻找帐户2,如果在输入框name =“ id”中输入2,我将得到所有具有数字2的结果。如果我要查找特定人员的姓名,然后键入名,然后输入另一个姓氏。.它将带出我想要的名字,但带其他结果时,带上我输入的姓氏。 How can I set a limit on the results I look for so either I get a match or not? 我该如何为寻找的结果设置一个限制,以便找到匹配结果? I am still learning. 我仍在学习。 thank you 谢谢
PS. PS。 valid to say, no where I can specify LIMIT 1.. 可以说有效,没有可以在其中指定LIMIT 1.的地方。
$searchFields = [];
foreach (['id', 'firstname', 'lastname', 'email'] as $searchField) {
if (!empty($_POST[$searchField])) {
$searchFields[$searchField] = $_POST[$searchField];
}
}
if (count($searchFields) > 0) {
$queryStr = "SELECT * FROM `Demo_Guests` WHERE 0";
foreach (array_keys($searchFields) as $fieldName) {
$queryStr .= " OR " . $fieldName . " LIKE :" . $fieldName ;
}
//var_dump($queryStr);
$stmt = $conn->prepare($queryStr);
foreach($searchFields as $fieldName => $fieldValue) {
$stmt->bindValue(':'. $fieldName, "%$fieldValue%", PDO::PARAM_STR);
}
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
//var_dump($result);
} else {
echo "";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
You can add LIMIT 1
to the end of $queryStr
. 您可以在$queryStr
的末尾添加LIMIT 1
。
$queryStr = "SELECT * FROM `Demo_Guests` WHERE 0";
foreach (array_keys($searchFields) as $fieldName) {
$queryStr .= " OR " . $fieldName . " LIKE :" . $fieldName ;
}
$queryStr .= " LIMIT 1";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.