mySQL all categories query in select statement

时间:2017-10-12 10:14:47

标签: php mysql

I've got table of categories:

Id category
1  cat 1
2  cat 2
3  cat 3 
etc.

I want to make select statement with category variable in php: $category with PDO:

for example:

$category = 1;

$this->db->query('SELECT (...)
       WHERE category.id = :category');
$this->db->bind(':category', $category);
$results = $this->db->resultset();

How can I make that if ($category = 0) all categories will be selected?

1 个答案:

答案 0 :(得分:0)

Use the following code

$category = 1;

$str = '';
if(!empty($category)) $str = " WHERE category.id = :category";

$this->db->query('SELECT (...)
       '.$str);

if(!empty($category))
$this->db->bind(':category', $category);
$results = $this->db->resultset();