Sum*_*pta 2 javascript php mysql web-services
假设我的网址是 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 + ";";
}
}
Run Code Online (Sandbox Code Playgroud)
现在假设我的URL有10个参数(或更多).在这种情况下,使用if-else并不是很好.如何在不使用这么多if-else语句的情况下生成查询?有没有更好的方法/脚本/库可以做这件事?
有很多方法可以做到这一点,但最简单的方法是遍历可接受的列,然后适当地追加.
// 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.
Run Code Online (Sandbox Code Playgroud)
如果你真的试图摆脱'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 );
Run Code Online (Sandbox Code Playgroud)
但是您可能希望运行实际的基准来确定这是否是一个更好的选择.
| 归档时间: |
|
| 查看次数: |
2709 次 |
| 最近记录: |