Reputation: 1868
I have a user list of 100 or so users and I'm trying to create a search field so I can find a certain user easier. I would like to search by multiple columns in the user database.
I tried creating this query but I'm pretty new to this and I'm not sure about all the OR statements.
Here is what i got.
My Search form:
<form action="search-users.php" method="GET" class="no-margin">
<label>Type in a keyword to search for a user.</label><br><br>
<input type="text" name="keywords" autocomplete="off" placeholder="Example: John Doe"><br>
<input type="submit" value="Search Users">
</form>
Then the action script:
<?php
if(isset($_GET['keywords'])){
$keywords = escape($_GET['keywords']);
$search = DB::getInstance()->query("
SELECT `username`,`first_name`,`last_name`,`unit`,`email`,`rent_own`,`city`,`zip`,`phone` FROM `users` WHERE
`username` LIKE '%{keywords}%' OR
`first_name` LIKE '%{keywords}%' OR
`last_name` LIKE '%{keywords}%' OR
`unit` LIKE '%{keywords}%' OR
`email` LIKE '%{keywords}%' OR
`rent_own` LIKE '%{keywords}%' OR
`city` LIKE '%{keywords}%' OR
`zip` LIKE '%{keywords}%' OR
`phone` LIKE '%{keywords}%'
");
}
?>
<!--SHOW HOW MANY RESULT ARE RETURNED-->
<h3 class="blue-tx" align="center">Found <?php echo $search->Count()?> results</h3>
<?php
if ($search->Count()){
foreach($search->results() as $s){
?>
....Display user results here.
<?php } } ?>
If someone could guide me through this a little. I would appreciate it.
Upvotes: 1
Views: 78
Reputation: 2916
You forgot $
in keywords variable
Change:
'%{keywords}%' => '%{$keywords}%'
Upvotes: 1
Reputation: 4749
Try this:
<?php
if(isset($_GET['keywords'])){
$keywords = escape($_GET['keywords']);
$search = DB::getInstance()->query("
SELECT `username`,`first_name`,`last_name`,`unit`,`email`,`rent_own`,`city`,`zip`,`phone` FROM `users` WHERE
`username` LIKE '%keywords%' OR
`first_name` LIKE '%keywords%' OR
`last_name` LIKE '%keywords%' OR
`unit` LIKE '%keywords%' OR
`email` LIKE '%keywords%' OR
`rent_own` LIKE '%keywords%' OR
`city` LIKE '%keywords%' OR
`zip` LIKE '%keywords%' OR
`phone` LIKE '%keywords%'
");
}
?>
<!--SHOW HOW MANY RESULT ARE RETURNED-->
<h3 class="blue-tx" align="center">Found <?php echo $search->Count()?> results</h3>
<?php
if ($search->Count()){
foreach($search->results() as $s){
?>
....Display user results here.
<?php } } ?>
Upvotes: 0