What if you use thinkphp to query the database to ignore query conditions that do not exist?

$condition there will be a time condition, this time condition is optional, now think if the time condition does not exist, how to remove the time condition? When the time condition exists, then add the query result of the time condition?

method 1: an error will be reported if the array does not exist.

public static function getHomeworkByStudentId($id, $conditions)
{
    $conditions["startTime"] = "2018-09-01";
    $conditions["endTime"]   = "2018-09-02";

    $result = self::where("id", "=", $id)
        ->whereTime("recordTime", ">", $conditions["startTime"])
        ->whereTime("recordTime", "<", $conditions["endTime"])
        ->select();

    return $result;
}

method 2: if the time condition does not exist, the time condition for generating sql will become 0, as follows:

SELECT * FROM `homework` WHERE `id` = "1" AND ( `recordTime` >= 0 AND `recordTime` <= 0 )
public static function getHomeworkByStudentId($id, $conditions)
{
    $conditions["startTime"] = "2018-09-01";
    $conditions["endTime"]   = "2018-09-02";

    $result =  self::where("id", ":id")
        ->whereTime("recordTime", ">=", ":startTime")
        ->whereTime("recordTime", "<=", ":endTime")
        ->bind($conditions)
        ->select();

    return $result;
}
Jun.10,2021

ThinkPHP 5.1 document, last conditional query.

https://www.kancloud.cn/manua.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1bef9bd-31cb2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1bef9bd-31cb2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?