Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a long query and have a lot of if statements - is there a more elegant way?

I have to build a query based on certain conditions. Is there a better way of doing it than the way I have done below? It works fine but I can see it getting out of hand fairly quickly if there were more conditions since I check if any previous conditions had been met every time I check a new one.

    $sql = "SELECT DISTINCT fkRespondentID FROM tblRespondentDayTime";

    if (!empty($day) || !empty($time) || !empty($sportID)) {

        $sql .= " WHERE";

        if (!empty($day)) {
            $sql .= " fldDay='$day'";
        }

        if (!empty($time)) {
            if (!empty($day)) {
                $sql .= " AND";
            }
            $sql .= " fldTime='$time'";
        }

        if (!empty($sportID)) {
            if (!empty($day) || !empty($time)) {
                $sql .= " AND";
            }
            $sql .= " fkRespondentID IN (SELECT fkRespondentID FROM tblRespondentSport WHERE fkSportID='$sportID')";
        }

    }
like image 491
birderic Avatar asked Aug 12 '10 18:08

birderic


People also ask

How long is too long SQL query?

If the query exceeds 8,192 characters, then the error message "SQL statement is too long" is displayed.


1 Answers

I would use the old "WHERE 1=1" trick; add this as the first condition, and then you can assume the "AND" condition on each statement that follows.

like image 57
DanP Avatar answered Sep 22 '22 00:09

DanP