¿Cómo seleccionar varios campos en función de una búsqueda GET?

I'm making a search site where the user can either search by Business Name or the table rows cat1, cat2,cat3. The "cat" rows are in the same table as the business name. I have it set up so I return business info if I search for the correct business. But I need to have it show businesses that have the category name you searched for.

**Basically what I'm asking is for a get search (php) to either search for the name of businesses or one of three categories.

Any Help, would be greatly appreciated... Here is my code In case you need it(Though I think this should be a pretty easy task, maybe not though, I'm a PHP Beginner)

            $var = $_REQUEST['search'];
            $trimmed = trim($var);
            $search = ucfirst($var);

        $result = mysql_query("SELECT * FROM gj WHERE name like '%$search%' ORDER by name") or trigger_error(mysql_error());
        $num_rows = mysql_num_rows($result);

And then I am using a while loop to get all the code from it.

 while($row = mysql_fetch_array($result))
        $addressmap = preg_replace('/\s/', '+',$address);
        $citymap = preg_replace('/\s/', '+',$city);


preguntado el 08 de enero de 11 a las 16:01

You need to use mysql_real_escape_string on ALL "untrusted" variables you use in SQL queries. This is an SQL injection attack waiting to happen. -

you should also be using $_GET no es $_REQUEST -

Ok I just changed it. Is there a difference? -

2 Respuestas

 $searchfields = array('name', 'cat1', 'cat2', 'cat3', )
 $cleandata = mysql_real_escape_string(trim(strtolower($_REQUEST['search'])));

 $where = array();
 foreach($searchfields as $field) {
     $where[] = 'lcase('.$field.') like \'%.$cleandata.%\'';

 $result = mysql_query('SELECT * FROM gj WHERE '.implode(' OR ', $where).' ORDER by name') or trigger_error(mysql_error());
 $num_rows = mysql_num_rows($result);

I've added a variable cleandata which contains the cleaned request data (to prevent SQL injection).

I've created a variable searchfields which can be easily expanded to search on more fields.

To search on more fields simply expand the array data:

 $searchfields = array('name', 'cat1', 'cat2', 'cat3', 'cat4', )

EDIT Added case insensitive


Note that since I have written this answer the community has begun the deprecation process de los antiguos mysql_*. Consulte la caja roja? Instead you should learn about declaraciones preparadas and use either PDO or MySQLi. If you can't decide, este artículo will help to choose. If you care to learn, here is a good PDO tutorial.

A rewrite of the above answer using PDO would look like something like the following:

$dbConnection = new PDO('mysql:dbname=dbtest;host=;charset=utf8', 'user', 'pass');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$searchfields = array('name', 'cat1', 'cat2', 'cat3', )

$where = array();
foreach($searchfields as $field) {
    $where[] = 'lcase(' . $field . ') LIKE :keyword';

$stmt = $dbConnection->prepare('SELECT * FROM gj WHERE ' . implode(' OR ', $where) . ORDER BY name);
    ':keyword' => '%' . trim(strtolower($_REQUEST['search'])) . '%',

Respondido 09 ago 12, 13:08

Dude, You are amazing...Thanks so much. - la_

Lets say, you want to search for bussines name 'Jake' and category 'php'.
URL for your request will be like this...


You need to have some column, thats is unique identifier of table row. In this example I use 'id' column. Edit it to your needs. Now lets set up your query...

$query = "SELECT * FROM `gj`
WHERE name LIKE '%{$_GET['name']}%'
AND `gj.id` IN (
    SELECT id FROM test
        cat1 LIKE '%{$_GET['category']}%' OR 
        cat2 LIKE '%{$_GET['category']}%' OR
        cat3 LIKE '%{$_GET['category']}%'
    // or edit this cat1 LIKE '%{$_GET['category']}%'
    // to cat1 = '{$_GET['category']}'
    // if you want to compare exact values

With this query you retrieve data from DB

 $result = mysql_query($query) or trigger_error(mysql_error());

Now do whatever you want with retrieved data.
Let me know the result ;-)

Respondido el 11 de enero de 11 a las 00:01

Matk it as an accepted answer, so other people will recognize it. This could help someone else :) - Andreyco

SQL Injection waiting to happen - PeeHaa

Mate, he is allowed to do anything with the query... I only showed him, how to build the query - Andreyco

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.