I have put together a for loop for a small search function I am building.
The code is as follows
$keyword = explode("+", $keywords);
for($i=0; $i <= count($keyword); $i++){
//check user table
$q = "SELECT id, username FROM ".TBL_USERS." WHERE username LIKE '%$keyword[$i]%'";
$result = $database->query($q);
while($row=mysql_fetch_assoc($result)){
extract($row);
echo "<a href='/profile.php?id=$id'>$username</a>";
}
}
When this runs, it is somehow retrieving all of the users from the database. Is there any obvious reason for this?
If $keywords = "gregg";
, would this still work as there wouldn't be a + sign (only one word). Either way, this still doesn't work when it has multiple words involved!
I can confirm the query works perfectly if the term 'gregg' is passed into it.
Thanks for reading, hope you can help.
Your for loop looks like:
for ($i=0; $i <= count($keyword); $i++)
This is going past the end of $keyword by one, so the last query the loop executes is "LIKE '%%'" which would return every row. To fix this, change it to:
for ($i=0; $i < count($keyword); $i++)
Also, you cannot do "$keyword[$id]". It must be "{$keyword[$i]}"
your index has count($keyword) - 1, not count($keyword);
$keyword = explode("+", $keywords);
for($i=0; $i <= count($keyword) - 1; $i++){
//check user table
$q = "SELECT id, username FROM ".TBL_USERS." WHERE username LIKE '%".$keyword[$i]."%'";
$result = $database->query($q);
while($row=mysql_fetch_assoc($result)){
extract($row);
echo "<a href='/profile.php?id=$id'>$username</a>";
}
}
and changed quotes
try this
$q = "SELECT id, username FROM ".TBL_USERS." WHERE username LIKE '%{$keyword[$i]}%'";
or better this
$q = "SELECT id, username FROM ".TBL_USERS." WHERE username LIKE '%" . $keyword[$i] . "%'";
Consider use OR
in the sql:
$keyword = explode("+", $keywords);
$keywords = array_map("mysql_real_escape_string", $keywords);
$q = "SELECT id, username FROM user WHERE username LIKE '%" . implode("%' OR username LIKE '%", $keywords) . "%';";
$result = $database->query($q);
while($row = mysql_fetch_assoc($result))
{
extract($row);
echo "<a href='/profile.php?id=$id'>$username</a>";
}