Searching Database with PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Foxy999
Forum Commoner
Posts: 45
Joined: Sat Mar 21, 2009 11:50 am

Searching Database with PHP

Post by Foxy999 »

I need to be able to search a row for a given string, but I am having trouble. This is what I have:

Code: Select all

 
$string = "toSearch";
while($row = mysql_fetch_array($result))
{
     if($row['name'] == $string)
     {
            echo "String found!";
     }
}
 
I need to add code so that if there are several words in the database and the $string matches at least one of the words then it will echo "String found!"


Foxy
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Searching Database with PHP

Post by jackpf »

That's a very inefficient way of going about this.

You should use the SQL LIKE clause instead.
Foxy999
Forum Commoner
Posts: 45
Joined: Sat Mar 21, 2009 11:50 am

Re: Searching Database with PHP

Post by Foxy999 »

So something like this:

"SELECT * FROM X LIKE ".$string."%"

for my query, I guess that will work.

Thanks for the help,

Foxy
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Searching Database with PHP

Post by jackpf »

The LIKE part goes in the WHERE section.

So, no like this:

Code: Select all

SELECT * FROM TABLE WHERE FIELD LIKE '%$string%'
Post Reply