1

I'm trying to figure out how can I build a query in PDO like this one

//...
$sql = array();
$sql[] = "SELECT * FROM `posts` WHERE `completed` = '1'";
if($this->is($_GET, 'category')) {
    $sql['category'] = "AND `category` = '".$_GET['category']."'";
}
if($this->is($_GET, 'tags')) {
    $sql['tags'] = "AND `tags` LIKE '%".$_GET['tags']."%'";
}
$sql[] = "ORDER BY `id` DESC LIMIT ".$offset.", ".$rows_per_page;
$query = $this->query(implode(" ", $sql));
//...

I tried something like that..

$sql = array();
$sql[] = "SELECT * FROM `posts` WHERE `completed` = :completed";
if($this->is($_GET, 'category')) {
    $sql['category'] = "AND `category` = :category";
}
$sql[] = "LIMIT 0, 5";

$this->db->query(implode(" ", $sql));
$this->db->bind(array(
    ':completed' => 1,
    ':category' => $this->is($_GET, 'category')
));
$fetch = $this->db->fetchAll();
print_r($fetch);

but there's a error that says I can not bind nonexistent variables "SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens" ...and with some research I figure out I can not bind before query

..so.. do you have any idea how can I do this?

  • 1
    Collect all the values needed (within the `if` clauses) in another variable array and pass that to `bind()`. – Sirko Apr 07 '15 at 18:25
  • 1
    You need `execute()` instead of `bind()` and you should fill your array conditionally as `:category` will not always be present. See for example: http://stackoverflow.com/a/29498254/42139 – jeroen Apr 07 '15 at 18:27

0 Answers0