user1762087
user1762087

Reputation: 460

Create mysql select - multiple parameters (some are unnecessary)

Let's asume I have following object in 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;
}

Problem is, that $home (or $user) could be empty string and in this case I want to include all homes (or users), not just columns, where home="" (or user="");

Do you have any suggestion how to do that? Or is this idea wrong? (I'm just beginner with PHP)

Upvotes: 0

Views: 169

Answers (2)

Kickstart
Kickstart

Reputation: 21513

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;
}

Upvotes: 0

Rob W
Rob W

Reputation: 9142

This is not the most elegant, and we should be using PDO prepared statements... but for sake of example:

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;
  }
}

Example test output:

$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();

Will yield:

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

Upvotes: 1

Related Questions