根据从另一个页面发送的值定义MYSQL查询

时间:2017-12-08 15:28:16

标签: php mysql get

我正在尝试根据通过URL从父页面发送的值的存在(或不存在)来设置MYSQL查询。变量如下:

        $startdate = $_GET["selectstartdate"];
        $enddate = $_GET["selectenddate"];
        $ensemble = $_GET["selectensemble"];
        $venue = $_GET["selectvenue"];
        $city = $_GET["selectcity"];

前两个将始终为非NULL,但其余三个的默认值为NULL,可以在父页面上重新定义,也可以不重新定义。所以,我需要做的是根据我收到的这些变量重构我的SQL查询。

如果仅发送前两个变量(并且所有其他变量都为NULL),则以下查询是正确的:

        $sql = "SELECT Concert.date, Ensemble.long_name, Concert.title, ensemble_web, Concert.info, Concert.repertoire, Venue.name, venue_web, Venue.address, Venue.city, Venue.map 
                FROM Concert, Ensemble, Venue
                WHERE Concert.ensemble_id = Ensemble.id AND Concert.venue_id = Venue.id
                AND Concert.date BETWEEN '$startdate' AND '$enddate'";

但是,如果例如$ ensemble不是NULL,那么我需要在查询中添加一个额外的行:

                AND Ensemble.short_name='$ensemble';

同样,如果$ venue不是NULL,那么我需要:

                AND Venue.name='$venue';

...当然,如果$ city不是NULL,那么我需要:

                AND Venue.city='$city';

我真的是最好的方法。非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

以下是您以更简单的方式管理您所在条件的答案:

<?php
// note that this mysqli_real_escape_string will prevent sql injection and $con is your connection variable
$startdate = mysqli_real_escape_string($con, $_GET["selectstartdate"]);
$enddate = mysqli_real_escape_string($con, $_GET["selectenddate"]);
$ensemble = mysqli_real_escape_string($con, $_GET["selectensemble"]);
$venue = mysqli_real_escape_string($con, $_GET["selectvenue"]);
$city = mysqli_real_escape_string($con, $_GET["selectcity"]);


$sql = "SELECT Concert.date, Ensemble.long_name, Concert.title, ensemble_web, Concert.info, Concert.repertoire, Venue.name, venue_web, Venue.address, Venue.city, Venue.map 
        FROM Concert, Ensemble, Venue
        WHERE Concert.ensemble_id = Ensemble.id AND Concert.venue_id = Venue.id
        AND Concert.date BETWEEN '$startdate' AND '$enddate'";
$where_clause = ["Concert.ensemble_id = Ensemble.id", "Concert.venue_id = Venue.id", "Concert.date BETWEEN '$startdate' AND '$enddate'"];

if(!empty($ensemble)) {
    $where_clause[] = "Ensemble.short_name='$ensemble'";
}

if(!empty($venue)) {
    $where_clause[] = "Venue.name='$venue'";
}

if(!empty($city)) {
    $where_clause[] = "Venue.city='$city'";
}

$sql .= " WHERE " . implode(" AND ", $where_clause);