mysql - How to query specific category or all categories inside the same query? -


i have table column name "category". in php, use sql prepare statement select records belonging specified category. category=? , add variable category value. works fine.

however, how can select categories within same query?

i tried using null , '' category value did not work. copying whole code part query might create spagetti code, wondering if there better option. there?

thanks!

building on @jamesmarks offering, simpler use query like

$query = "select * table category = ? or 1 = ?;" 

then pass $category first parameter, , either 1 or 0 second parameter. if pass 1, second term becomes 1 = 1. that's true, whole expression true. if pass 0, second term 1 = 0 , that's false, whole expression true if category = $category matches.

that's simpler , better style designating special value 0 "any category."

an alternative solution build query dynamically:

$where = array(); if ($category) {     $where[] = "category = ?";     $params[] = $category; }  ... perhaps add more terms $where conditionally ...  $query = "select * table"; if ($where) {     $query .= " " . implode(" , ", $where); } 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -