php - Altering mysql query based on variable -


so making click based search tool. nothing fancy , works great long pick @ least 1 thing available categories. want change there no mandatory categories pick from, if want pick category cpu, give results aswell.

this have input:

<form action="search.php" method="get">  <input value="i3"  name="cpu[]" type="checkbox">i3  <input value="i5"  name="cpu[]" type="checkbox">i5 <br> <input value="4gb"  name="ram[]" type="checkbox">4gb   <input value="8gb"  name="ram[]" type="checkbox">8gb<br> <input value="1tb"  name="storage[]" type="checkbox">1tb  <input value="500gb"  name="storage[]" type="checkbox">500gb<br> <input type="submit" value="search" class="submit" /> 

this part gathers clicked checkboxes (i left out cpu , ram parts since same):

if(isset($_get['storage'])){   if (is_array($_get['storage'])) {     foreach($_get['storage'] $storage_value){       $storage_term = trim($storage_value);       $storage_term_array[] = $storage_term;     if (!empty($storage_term)) {         $storage_bits[] = "`storage` '%$storage_term%'";     } } } } else $storage_bits="0"; 

and mysql_query goes this:

$res=mysql_query("select * laptop  (".implode(' or ', $cpu_bits).")   , (".implode(' or ', $ram_bits).")  , (".implode(' or ', $storage_bits).") , visibility=1"); 

this returns:

(`cpu` '%i5%') , (`ram` '%8gb%') , (`storage` '%1tb%' or `storage` '%500gb%') 

this code working, said before need pick @ least 1 checkbox per category. how exclude lets and (".implode(' or ', $storage_bits)." part if $storage_bits="0"?

so far have had no luck case

$res=mysql_query("select * laptop  (".implode(' or ', $cpu_bits).")   , (".implode(' or ', $ram_bits).")  (case when ($storage_bits=0) 'and 1=1' else 'and (".implode(' or ', $storage_bits)."' end ) , visibility=1"); 

and not if working me.

$res=mysql_query("select * laptop  (".implode(' or ', $cpu_bits).")   , (".implode(' or ', $ram_bits).")  if($storage_bits=0,'1=1','and (".implode(' or ', $storage_bits).") , visibility=1"); 

it gives me no syntax errors whatsoever, doesn't give results. gives? feel missing quotation marks or pitiful cant seem wrap head around it. thanks!

try this:

$whereclause = "where visibility = 1"; if($cpu_bits != '0'){     $whereclause .= " , (".implode(' or ', $cpu_bits).")"; } if($ram_bits != '0'){     $whereclause .= " , (".implode(' or ', $ram_bits).")"; } if($storage_bits != '0'){     $whereclause .= "and (".implode(' or ', $storage_bits).")"; } $res=mysql_query("select * laptop".$whereclause); 

doing this, preventing empty fields go in there clause.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -