假设我的网址为http://something.com/products.php?brand=samsung&condition=new
对于上述查询,我在PHP中使用isset()
和$_GET[])
函数以及许多if-else
语句来生成用于显示满足搜索条件的产品的sql查询。
例如:如果我只处理brand
和condition
个参数,那么这就是我将如何生成查询:
$sql = "select * from products where 1=1 ";
if(isset($_GET['brand']))
{
if(isset($_GET['condition']))
{
$sql = $sql + "and brand=".$_GET['brand']." and condition=".$_GET['condition'];
}
}
else
{
if(isset($_GET['condition']))
{
$sql = $sql + "and condition=".$_GET['condition'];
}
else
{
$sql = $sql + ";";
}
}
现在假设我的网址有10个参数(或更多)。在这种情况下,使用if-else
并不是很好。如何在不使用这么多if-else
语句的情况下生成查询?有没有更好的方法/脚本/库可以做这件事?
答案 0 :(得分:5)
有很多方法可以做到这一点,但最简单的方法是遍历可接受的列,然后适当地附加。
// I generally use array and implode to do list concatenations. It avoids
// the need for a test condition and concatenation. It is debatable as to
// whether this is a faster design, but it is easier and chances are you
// won't really need to optimize that much over a database table (a table
// with over 10 columns generally needs to be re-thought)
$search = array();
// you want to white-list here. It is safer and it is more likely to prevent
// destructive user error.
$valid = array( 'condition', 'brand' /* and so on */ );
foreach( $valid as $column )
{
// does the key exist?
if( isset( $_GET[ $column ] ) )
{
// add it to the search array.
$search[] = $column . ' = ' . mysql_real_escape_string( $_GET[ $column ] );
}
}
$sql = 'SELECT * FROM TABLE_NAME WHERE ' . implode( ' AND ', $search );
// run your search.
如果你真的试图摆脱'if'语句,你可以使用它:
$columns = array_intersect( $valid, array_keys( $_GET ) );
foreach( $columns as $column )
{
$search[] = $column . ' = ' . mysql_real_escape_string( $_GET[ $column ] );
}
$sql = 'SELECT * FROM TABLE_NAME WHERE ' . implode( ' AND ', $search );
但您可能希望运行实际的基准来确定这是否是一个更好的选择。