Search code examples
phpmysqlistrpos

strpos() with mysqli query


$text = "Mike is registered on Website";

Mike is a registered user on a website and I want to find his name with strpos()

$find = $db->query("SELECT username FROM users");
$finduser = $find->fetch_object();

if(strpos($text, $finduser->username) !== false) {
  echo $finduser->username." is a user on Website.";
}

But it doesn't display the echo Mike is a user on Website.. I don't know if I'm doing everything correct.

Thank you.


Solution

  • To answer your question, let me assume that you want to search all your user in database if it in the text (string) or not.

    So what you want to do is loop each row of your database user and check if the username is in the text. Here's how:

    while ($finduser = $find->fetch_object()) // Loop all of your database row
    {
       if(strpos($text, $finduser->username) !== false) {
         echo $finduser->username." is a user on Website.";
       }
    }
    

    What your code provide is only check for row one. Here link for the php doc http://php.net/manual/en/mysqli-result.fetch-object.php