0

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の初心者です)

4

2 に答える 2

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'
于 2013-07-01T20:58:28.327 に答える
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;
}
于 2013-07-01T21:07:55.880 に答える