我正在尝试创建一个函数来使用特定条件搜索我的数据库。
function searchOrders($keywords, $criteriaId, $dateEntered, $statusID)
那是我打算使用的功能,我想构建一个查询来搜索每个变量,但也将它们组合起来。我想知道最好的方法是什么?
例如,他们不输入关键字但确实输入了criteriaId,或者他们同时输入了它们但省略了日期和状态。
任何想法都会受到赞赏,因为我还没有构建搜索功能。
这很简单。只需从查询字符串中获取您的请求变量。如果它们不存在,请将它们设置为 "" 或 NULL....
$keywords = $_GET["keywords"];
$criteriaId = $_GET["criteriaId"];
$dateEntered = $_GET["dateEntered"];
$statusID = $_GET["statusID"];
...并调用函数:
$orders = searchOrders($keywords, $criteriaId, $dateEntered, $statusID);
在 searchOrders 函数中,您可以检查任何参数的值是否为“”(空白)或 NULL 并相应地创建您的 SQL 查询。
这里的诀窍是使用where和关键字。(假设您只需要一个 where / 和条件查询,并且如果它的值不是空白或 NULL 则包含一个参数)
public function searchOrders($keywords, $criteriaId, $dateEntered, $statusID)
{   
    $query = "select * from orders";
    $condition = " where ";
    if (!is_null($keywords)) {
        $query .= $condition . "keywords like '$keywords'";
        $condition = " and ";
    }
    if (!is_null($criteriaId)) {
        $query .= $condition . "criteriaId = $criteriaId";
        $condition = " and ";
    }
    if (!is_null($dateEntered)) {
        $query .= $condition . "dateEntered <= #$dateEntered#";
        $condition = " and ";
    }
    if (!is_null($statusID)) {
        $query .= $condition . "statusID = $statusID";
    }
    return mysql_query($query) or die (mysql_error);
}
希望这可以帮助!
维韦克
例如,使用简单的 mysql,您可以像这样构建一些:
调用一个函数来获取一些数据
$data = selectSome("ID_User = '". $iduser ."' AND Situation != 0", 'table_example', 'Id_User, Name, Description, null, 'ID_User DESC', null);
/*Process $data */
功能
public function selectSome($SQL, $table = null, $fields = "*", $group = null, $order = null, $limit = null)
{       
    if (!is_null($group)) {
        $SQL .= " GROUP BY ". $group;
    }
    if (is_null($order)) { 
        $SQL .= "";     
    } elseif ($order === "DESC") {
        $SQL .= " ORDER BY $this->primaryKey DESC";
    } elseif (!is_null($order)) {  
        $SQL .= " ORDER BY ". $order;
    } elseif ($order === "") { 
        $SQL .= " ORDER BY $this->primaryKey";
    }
    if ($limit) {
        $SQL .= " LIMIT ". $limit;
    }
    $query = "SELECT $fields FROM $table WHERE $SQL";
    return mysql_query($query) or die (mysql_error);
}
这是一个基本示例,可以更改一些值并获得您想要的功能并将MYSQL更改为PDO或MYSQLI。
尝试这样的事情我不太了解,但这是我找到它的地方
选择名称、价格、warranty_available、exclusive_offer FROM Products UNION ALL SELECT name、price、warranty_available、exclusive_offer FROM Services
尝试像我的东西:
$sql = mysql_query("select * from colleges where Campus_Name like '%$term%' or Campus_Address like '%$term%' or 
    Campus_State like '%$term%' or Campus_City like '%$term%' or Campus_Zip like '%$term%' ");