I have a users table in MySQL and would like a search by name. Right now I have the following code:
Please check the below code.
<?php
$search = isset($_GET['q']) ? $_GET['q'] : '';
$search = strtoupper($search);
$search = strip_tags($search);
$search = trim($search);
$split_words = explode(" ", $search);
$query = "SELECT * FROM `users`";
if(count($split_words) > 0){
$query .= " WHERE "
for($i=0 ; $i < $split_words; $i++){
$query .= " name LIKE ? OR ";
}
$query = substr($query , 0, -3); //Remove last 3 characters OR with space
array_walk($split_words,"addPercentage");
$query->execute($split_words);
}else{
$query->execute();
}
$result = $query->rowCount();
echo $result;
function addPercentage(&$value,$key)
{
$value = "%".$value."%" ;
}
?>
You shouldn't use @ to silence errors it is a bad practice, check if the value is set. The example below should work, but the results might not be all that relevant.
$search = isset($_GET['q']) ? $_GET['q'] : '';
$search = strtoupper($search);
$search = strip_tags($search);
$search = trim($search);
$words = explode(' ', $search);
$words_condition = array();
$arguments = array();
foreach ($words as $word) {
$words_condition[] = 'name LIKE ?';
$arguments[] = '%'.$word.'%';
}
$query = $con->prepare('SELECT * FROM `users` WHERE '.implode(' OR ', $words_condition));
$query->execute($arguments);
$result = $query->rowCount();
echo $result;
$words = explode(" ", $search);
$i = 0;
while($words[i] != null)
{
//Query where name LIKE words[i]
}