简体   繁体   中英

How to select multiple fields based on a GET search?

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)

            include('config.php');
            $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))
        {
        $id=$row['id'];
        $name=$row['name'];
        $phone=$row['phone'];
        $website=$row['website'];
        $city=$row['city'];
        $address=$row['address1'];
        $zipcode=$row['zipcode'];
        $addressmap = preg_replace('/\s/', '+',$address);
        $citymap = preg_replace('/\s/', '+',$city);

        echo"
 include('config.php');
 $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


EDIT Added PDO

Note that since I have written this answer the community has begun the deprecation process of the ancient mysql_* . See the red box ? Instead you should learn about prepared statements and use either PDO or MySQLi . If you can't decide, this article 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=127.0.0.1;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);
$stmt->execute(array(
    ':keyword' => '%' . trim(strtolower($_REQUEST['search'])) . '%',
));

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

http://yourdomain.com/search.php?name=Jake&category=php


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
    WHERE 
        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 ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM