Reputation: 5
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. 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. valid to say, no where I can specify 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();
}
}
Upvotes: 0
Views: 56
Reputation: 780779
You can add LIMIT 1
to the end of $queryStr
.
$queryStr = "SELECT * FROM `Demo_Guests` WHERE 0";
foreach (array_keys($searchFields) as $fieldName) {
$queryStr .= " OR " . $fieldName . " LIKE :" . $fieldName ;
}
$queryStr .= " LIMIT 1";
Upvotes: 1