这不是最优雅的,我们应该使用 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'