PHP Mysql简化

时间:2012-12-17 17:08:48

标签: php mysql

任何人都可以帮我简化吗?我有一个页面用于查看表中的一堆数据,该页面应该通过GET调用接受不同的值。我只想稍微减肥一下。代码再次起作用,这对我来说只是意大利面。

if(!$_REQUEST['foo']){
    $bar = $_REQUEST['bar'];
    if($bar=='all'||!$bar){ $stmt = "SELECT * FROM table
        WHERE qty > 0  and
             somedate >= \"{$start}\"  and
             somedate <= \"{$end}\"
        ORDER BY id desc
        ";}
    else{
    $stmt = "SELECT * FROM table
        WHERE qty > 0  and
             somedate >= \"{$start}\"  and
             somedate <= \"{$end}\"  and
             bar = '$bar'
        ORDER BY id desc
        ";}
}
else{
     switch($_REQUEST['foo']){
       case 'all':
        $stmt = "SELECT * FROM table
          WHERE qty > 0  and
          somedate >= \"{$start}\"  and
          somedate <= \"{$end}\"
          ORDER BY id desc";
        break;
     case 'open':
      $stmt = "SELECT * FROM table
          WHERE qty > 0  and
          closd = 0 and
          somedate >= \"{$start}\"  and
          somedate <= \"{$end}\"
          ORDER BY id desc";
      break;
     case 'closed':
      $stmt = "SELECT * FROM table
          WHERE qty > 0  and
          closd = 1 and
          somedate >= \"{$start}\"  and
          somedate <= \"{$end}\"
          ORDER BY id desc";
      break;
}}

1 个答案:

答案 0 :(得分:2)

假设您在程序中进行了一些健全性检查,这将处理switch()。

<?php // RAY_temp_andy_foster.php
error_reporting(E_ALL);

$closd = '1=1';
switch($_REQUEST['foo'])
{
    case 'all':    $closd = '1=1';       break;
    case 'open':   $closd = 'closd = 0'; break;
    case 'closed': $closd = 'closd = 1'; break;
}
$stmt = "SELECT * FROM table WHERE qty > 0 AND somedate >= \"{$start}\"  AND somedate <= \"{$end}\" AND $closd ORDER BY id desc";

的var_dump($语句);

HTH,~Ray