我有一个可搜索的众议院和参议院数据库,我只想制作一个可以搜索该数据库的简单网页。唯一的问题是,虽然我很乐意编写 SQL 选择语句,但我如何正确地格式化它们以便在 PHP 中使用?
例如,这是我按州选择参议员的单选按钮:
$sql = "";
if ($_POST['pkChamber'] == "Senate") {
if ($_POST['pkParty'] == "Y") {
$sql = SELECT * FROM senateinfo
WHERE state = (Variable = "stname")
ORDER BY last_name, first_name');
}
else
{
$sql = SELECT * FROM senateinfo
WHERE state = (Variable = "stname")
ORDER BY last_name, first_name
}
}
最佳答案
我不确定你要什么,但我有一个可靠和安全的动态构建 WHERE 语句的好例子:
$w = array();
$where = '';
if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'";
if (count($w)) $where = "WHERE ".implode(' AND ',$w);
$query = "select * from table $where";
希望这对您有所帮助。
关于php - PHP 中的基本 SQL Select 语句格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5291047/