根据用户输入

时间:2016-02-10 20:42:12

标签: php mysql

假设用户只输入了一位艺术家进行搜索,如何让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);

1 个答案:

答案 0 :(得分:1)

很简单,您可以分阶段构建查询字符串。忽略您的sql injection attack漏洞,假设所有选项都应AND,您可以执行以下操作:

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

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