创建mysql select - 多个参数(有些是不必要的)

时间:2013-07-01 20:53:28

标签: php mysql select

让我假设我在PHP中有以下对象:

class param{
 public $home; //set by another function
 public $user; //set by another function
 public function createRequest(){
//in this function I want to create mysql string with $home and $user
  $sql = "select * FROM table WHERE home =".$this->home." AND user=".$this->user;
  return $sql;
}

问题是,$ home(或$ user)可能是空字符串,在这种情况下,我想要包括所有家庭(或用户),而不仅仅是列,其中home =“”(或user =“”);

你有什么建议怎么做吗?或者这个想法是错的? (我只是初学者用PHP)

2 个答案:

答案 0 :(得分:1)

这不是最优雅的,我们应该使用PDO编写的语句......但是为了举例:

class param{
  public $home; //set by another function
  public $user; //set by another function
  public function createRequest(){
    //in this function I want to create mysql string with $home and $user
    $sql = "select * FROM table";
    if(strlen($this->home) || strlen($this->user)) {
      $sql .= " WHERE ";
      $and = array();
      if(strlen($this->home))
        $and[] = " home='".$this->home."' ";
      if(strlen($this->user))
        $and[] = " user='".$this->user."' "; 
      $sql .= implode(" AND ", $and);
    }
    return $sql;
  }
}

示例测试输出:

$p = new param;
echo $p->createRequest();
echo "<br>";

$p->home = "foo";
echo $p->createRequest();
echo "<br>";

$p->user = "bar";
echo $p->createRequest();
echo "<br>";

$p->home = "";
echo $p->createRequest();

将屈服:

select * FROM table
select * FROM table WHERE home='foo' 
select * FROM table WHERE home='foo' AND user='bar' 
select * FROM table WHERE user='bar'

答案 1 :(得分:0)

class param{
 public $home; //set by another function
 public $user; //set by another function
 public function createRequest(){
//in this function I want to create mysql string with $home and $user
    $ClauseArray = array(' 1 = 1 ');
    if ($this->home != '') $ClauseArray[] = " home = '".$this->home."' ";
    if ($this->user != '') $ClauseArray[] = " user = '".$this->user."' ";
    $sql = "select * FROM table WHERE ".implode('AND', $ClauseArray);
    return $sql;
}