簡體   English   中英

根據用戶輸入選擇正確的SQL查詢

[英]Choosing the correct SQL query based off user input

假設用戶僅輸入了一個藝術家來進行搜索,那么我如何使PHP識別出該用戶僅在尋找藝術家,因此應該僅針對該藝術家設置查詢。 我目前的工作方式有效,但是當用戶想要各種搜索選項時,它的效率很低。

$artist = $_POST["artistSearch"];
$topic= $_POST["topicSearch"];
$date = $_POST["dateSearch"];
$title = $_POST["titleSearch"];

$artistLength = strlen($artist);
$topicLength = strlen($topic);
$dateLength = strlen($date);
$titleLength = strlen($title);

if ($artistLength>2 && $topicLength<2 && $dateLength<2 && $titleLength<2) {
    $sql=("Select * FROM music WHERE artist = '$artist' ORDER BY date");
}

if ($artistLength>2 && $topicLength>2 && $dateLength<2 && $titleLength<2) {
    $sql=("Select * FROM music WHERE artist = '$artist' AND topic = '$topic' ORDER BY date");
}

if ($artistLength>2 && $topicLength>2 && $dateLength>2 && $titleLength<2) {
    $sql=("Select * FROM music WHERE artist = '$artist' AND topic = '$topic' AND date = '$date' ORDER BY date");
}

if ($artistLength>2 && $topicLength>2 && $dateLength>2 && $titleLength>2) {
    $sql=("Select * FROM music WHERE artist = '$artist' AND topic = '$topic' AND date = '$date' AND title = '$title' ORDER BY date");
}

$result = mysqli_query($con,$sql);

很簡單,您可以分階段構建查詢字符串。 忽略您的sql注入攻擊漏洞,並假設所有選項都應進行AND運算,則可以執行以下操作:

$options = array();
if ($artist) {
   $options[] = "artist = '$artist'";
}
if ($topic) {
   $options[] = "topic = '$topic'";
}
etc...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM