我有一個搜索功能,可以讓你輸入最後一個,第一個和中間名的不同類型框。我沒有任何代碼問題,但有誰知道如何優化它?PHP/MySQL如何設置更簡單的SELECT查詢?
的代碼有多種,如果是發現了什麼文本框是unempty並隨後在WHERE作爲你可以看到下面的語句:
$where1 = $_POST['firstname'];
$where2 = $_POST['midname'];
$where3 = $_POST['lastname'];
if(!empty($where1) && empty($where2) && empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE firstname = '$where1'");
} else if(!empty($where1) && !empty($where2) && empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE firstname = '$where1' AND midname = '$where2'");
} else if(!empty($where1) && !empty($where2) && !empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE firstname = '$where1' AND midname = '$where2' AND lastname = '$where3' ");
} else if(!empty($where1) && empty($where2) && !empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE firstname = '$where1' AND lastname = '$where3' ");
} else if(empty($where1) && !empty($where2) && !empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE lastname = '$where3' AND midname = '$where2' ");
} else if(empty($where1) && !empty($where2) && empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE midname = '$where2'");
} else if(empty($where1) && empty($where2) && !empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE lastname = '$where3'");
}
您可能不想「簡化」代碼。多重查詢將允許MySQL利用特定於每組條件的索引。 – 2014-10-27 03:07:07
搜索*「PHP的SQL查詢生成器」*。當你在它,請參閱http://php.net/manual/language.operators.string.php – Phil 2014-10-27 03:07:39
這屬於http://codereview.stackexchange.com/ – EternalHour 2014-10-27 03:22:23