我遇到了這個問題,我試圖想出最好和最有效的解決方案。我有一個19個不同的輸入的PHP網站,他們都是可選的,我使用get方法。有了這些輸入,我必須找到與數據庫匹配並返回的信息。我遇到的問題是創建可以工作的查詢。使用php創建sql查詢
$query = "SELECT * FROM TEST.table";
if(($_GET['Transmission_Line_Designation'] ==="") && ($_GET['Switch_Number'] === "") && ($_GET['Telecom_Circuit_Number'] === "")
&& ($_GET['Transmitter_Frequency'] === "") && ($_GET['Receiver_Frequency'] === "") && ($_GET['power_level'] === "")
&& ($_GET['Phase'] === "") && ($_GET['Modulate'] === "") && ($_GET['trap_type'] === "") && ($_GET['line_tuner_type'] === ""))
//checks if there were no input, if there werent any, display all columns and rows from the data base
{
}
else
{
這是我遇到的問題,如果用戶輸入第一輸入,它會工作,但是,如果用戶離開第一輸入欄,散發出來的查詢是「裏和」一些東西,我正在考慮使用很多if循環來檢查條件並添加一個標誌,但我確信有一個更簡單的方法來完成它。
$query.= " where ";
if
$query .= ($_GET['Transmission_Line_Designation'] === "") ? '' : 'Line_Designation = "'.$_GET['Transmission_Line_Designation'].'"';
$query .= ($_GET['Switch_Number'] === "") ? '' : ' and Switch_Number = "'.$_GET['Switch_Number'].'"';
$query .= ($_GET['Telecom_Circuit_Number'] === "") ? '' : ' and Telecom_Circuit_Number = "'.$_GET['Telecom_Circuit_Number'].'"';
$query .= ($_GET['Transmitter_Frequency'] === "") ? '' : ' and Transmitter_Frequency = "'.$_GET['Transmitter_Frequency'].'"';
$query .= ($_GET['Receiver_Frequency'] === "") ? '' : ' and Receiver_Frequency = "'.$_GET['Receiver_Frequency'].'"';
$query .= ($_GET['power_level'] === "") ? '' : ' and power = "'.$_GET['power_level'].'"';
$query .= ($_GET['Voltage'] === "") ? '' : ' and voltage = "'.$_GET['Voltage'].'"';
$query .= ($_GET['Phase'] === "") ? '' : ' and Phase= "'.$_GET['Phase'].'"';
$query .= ($_GET['Modulate'] === "") ? '' : ' and Modulate = "'.$_GET['Modulate'].'"';
$query .= ($_GET['trap_type'] === "") ? '' : ' and trap = "'.$_GET['trap_type'].'"';
$query .= ($_GET['line_tuner_type'] === "") ? '' : 'and ltunner = "'.$_GET['line_tuner_type'].'"';
echo $query;
}
謝謝你們的幫助提前,我很感激。
將來你可能會考慮爲你的SQL使用預處理語句。成爲SQL注入的受害者從來沒有樂趣。 – CountMurphy