简体   繁体   中英

PHP to create MySQL query from URL query

I have a relatively small search form that I want people to use to search my SQL database.

The only way I've done this before was with a billion nested if statements. Is there a better way to do this?

I am parsing my URL query string, so I have my variables of say:

$city
$bedrooms
$elementaryschool

If I were to just try to try:

$sql = "SELECT * FROM $table_name WHERE ";

if(isset($city)) {
    $sql .= " `City` LIKE " . $city;
}
if(isset($bedrooms)) {
    $sql .= " AND `Bedrooms` >= " . $bedrooms;
}
if(isset($elementaryschool)) {
    $sql .= " AND `ElementarySchool` = " . $elementaryschool;
}

Then I run into an issue when $city isn't set because my query ends up with "SELECT * FROM $table_name WHERE AND Bedrooms >= $bedrooms"

That wouldn't exactly work. What are my options?

I completely understand how to do it if I am including all parameters in my query, which seems to be what all previous questions have asked. But how do I do this when not all fields will have a value? I have a total of 12 possible fields to use for searching, and they can search by just 1 or by all 12.

As I mentioned before, all of the questions I have been able to find refer to coming up with one static SQL query, instead of one that will have varying number of parameters.

I would go with:

$sql = "SELECT * FROM $table_name";
$where = array();
$params = array();

and then:

if(isset($city)) {
    $where[] = "City LIKE ?";
    $params[] = $city;
}

if(isset($bedrooms)) {
    $where[] = "Bedrooms >= ?";
    $params[] = $bedrooms;
}

if(isset($elementaryschool)) {
    $where[] = "ElementarySchool = ?";
    $params[] = $elementaryschool;
}

and finally:

if(!empty($where)) {
    $sql .= "WHERE " . implode(" AND ", $where);
}

$result = $db->prepare($sql)->execute($params);

PLEASE NOTE that here, since I do not know what kind of database layer/abstraction you are using, $db represents the database connection, prepare() is used to create a prepared statement, and execute() tu run it, as you would do using PDO ; this also protects against SQL injection.

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