假设我在 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 的初学者)
最佳答案
这不是最优雅的,我们应该使用 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'
关于php - 创建mysql select - 多个参数(有些是不必要的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17413506/