简体   繁体   中英

Rewrite query depending on GET parameters

I'm working on a search engine on my website. Users can add on criteria which is submitted with a GET in the url.

When users select for example 1 criteria, it looks like this:

localhost/search.php?course=1&price=&name=

They have 3 criteria they can select, so as you see he only selected COURSE.

Now I have to select from the database according to the criteria so my code looks like this:

if ($_GET['price'] > 0 && $_GET['name'])
{
    $search_price = $_GET['price'];
    $search_name = $_GET['name'];

    $result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id' AND price < $search_price AND name LIKE '%$search_name%'");
}
elseif ($_GET['price'] > 0)
{
    $search_price = $_GET['price'];

    $result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id' AND price < $search_price");
} 
elseif ($_GET['name'])
{
    $search_name = $_GET['name'];

    $result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id' AND name LIKE '%$search_name%'");
}
else 
{
    $result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id'");
}

while ($row2 = mysql_fetch_assoc($result2))
                                        {
.....

But this can not be the correct way, because if eventually users can select 10 criteria this is going to be a very long code

How do I fix this?

What I would do is dynamically create the sql query,and then execute it at the end. So something like this

$query_string = "SELECT blahblah, blahblah, blah blah from blahx where 1=1 ";
$where = "";

if(isset($_GET['somecriteria']))
{
    $where .= " AND blahblah = $_GET['somecriteia'] ";
}
if(isset($_GET['someOTHERcriteria']))
{
    $where .= " AND blahblah=$_GET['someOTHERcritera'] ";
}
mysql_query($query_string . $where);

etc.. Take note this is just to show you how to achieve your objective. This is obviously prone to SQL Injection attacks and you'd have to clean the stuff up.

Use $_post to send larger amounts of information to the php script. When using get you should create the url to include get calls only if they are populated. As such if no price is selected the url should not include "price=". This will cause problems with your receiving script.

Your database script can be done with one call including only the selected criteria.

Myqsl has been depreciated, you need to look into Myqsli or PDO

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