相同功能在同一查询中传递不同的参数同时获得两个输出

时间:2015-09-03 11:26:43

标签: php postgresql function return parameter-passing

我发送两个参数From=2015-08-01To=2015-08-31工作正常。然后如何传递参数(From2=2015-04-01 and To2 =2015-08-31)并同时获取两个输出。请不要写任何其他功能。请告诉我。

这是我的output.php

  $res1=$con->selectnonschoolround1($From,$To);
  while($row=pg_fetch_array($res1))
  {
    $r1=$row['non_slsc_qty'];
    $r2=$row['non_slst_qty'];
    $r3=$row['non_slot_qty'];
    $r4=$row['non_slsc_ben'];
    $r5=$row['non_slst_ben'];
    $r6=$row['non_slot_ben']; 
    $Total_qty_non_r1=$row['total_qty']; 
    $Total_ben_non_r1=$row['total_ben']; 
  }

这是class.php

class DB_con
{

  function __construct()
  {
    $db = pg_connect("host=localhost port=5432 
    dbname=mydb  user=postgres password=123");
  }
  public function selectnonschoolround1($From,$To)
  {
      $res1=pg_query("SELECT
      SUM(non_slsc_qty) as non_slsc_qty,
      SUM(non_slst_qty) as non_slst_qty,
      SUM(non_slot_qty) as non_slot_qty,
      SUM(non_slsc_ben) as non_slsc_ben,
      SUM(non_slst_ben) as non_slst_ben,
      SUM(non_slot_ben) as non_slot_ben,
      SUM(non_slsc_qty+non_slst_qty+non_slot_qty) AS total_qty,
      SUM(non_slsc_ben+non_slst_ben+non_slot_ben) AS total_ben
      FROM table  where date BETWEEN '$From' AND '$To'");
      return $res1;
  }
}

1 个答案:

答案 0 :(得分:0)

将函数参数作为数组传递,然后需要使用PHP函数is_array()检查参数是否为数组。如果它的数组然后遍历该数组并使用"从"执行查询。和"到"索引但是,在这种情况下,您需要从执行的查询返回一个数组。如果它不是一个数组,请将代码保留在其他部分中。在此,您可以对多个值或单个值使用相同的函数。请记住,参数应该是正确的。希望这会帮助你:)

尝试使用此代码并根据需要进行更改:)。

class DB_con
{

    function __construct()
    {
        //code
    }

    public function selectNonSchoolRound1($arr, $from = '', $to = '')
    {
        if (is_array($arr)) {
            $returnArr = array();
            foreach ($arr as $ars) {
                $res1 = pg_query("your query using ".$ars['from'].$ars['to']);
                array_push($returnArr, $res1);
            }
            return $returnArr;
        } else {
            $res1 = pg_query("your query using ".$from.$to.'variabls');
            return $res1;
        }

    }

}

try {
    $arr = array('0' => 
        array('from' => '2015-08-01', 'to' => '2015-08-31'), 
        '1' => array('from' => '2015-08-01', 'to' => '2015-08-31')
    );
    $obj = new DB_con();
    $result = $obj->selectNonSchoolRound1($arr);
    // loop here with the $result variable
} catch (Exception $ex) {
    echo $ex->getMessage();
}