Re: Select Query with Multiple Optional Values

From: Date: Sat, 21 Mar 2009 22:48:34 +0000
Subject: Re: Select Query with Multiple Optional Values
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-290512@lists.php.net to get a copy of this message
On Sat, 2009-03-21 at 10:30 -0700, benc11@gmail.com wrote: > Trying to find best way to accomplish following scenario. Looking to search > inventory through a POST form, have the following optional fields to search > by: Product Name, Color, Size, and Status. Search maybe for the Product > Name and/or Color or they may search for just the Color or all 4 fields. I > am trying to find the most efficient way to do this without having 100 > different if statements. <?php $where = array( '1 = 1' ); if( !empty( $_POST['name'] ) ) { where[] = 'name = '.$db->quote( $_POST['name'] ); } if( !empty( $_POST['colour'] ) ) { where[] = 'colour = '.$db->quote( $_POST['colour'] ); } if( !empty( $_POST['size'] ) ) { where[] = 'size = '.$db->quote( $_POST['size'] ); } if( !empty( $_POST['status'] ) ) { where[] = 'status = '.$db->quote( $_POST['status'] ); } $query = "SELECT " ." * " ."FROM " ." inventory " ."WHERE " ." (".implode( ") AND (", $where ).")"; ?> Cheers, Rob. -- http://www.interjinn.com Application and Templating Framework for PHP

« previous php.general (#290512) next »