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

标签 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 的初学者)

最佳答案

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

相关文章:

mysql - 如何使用MySQL选择每天的最后一条记录

php - 需要帮助为 select 语句编写 SQL 查询

mysql - 多次插入 Mysql Node JS 中的 resultId

css - Opera 选择背景图像不显示

mysql - mysql中两个相同表的区别

php - 无法在 Drupal 中加载自定义 JS

php - 表单 POST 数据循环如何分配变量并与数据库进行比较

javascript - 您没有选择要上传的文件。 ajax 代码点火器

php - 一个更好的 php array_merge

javascript - 如何从 Iframe 内部的选择框中获取选定的值,并将其显示在外部?