0

Example: the user fills in everything but the product name.

I need to search on what is supplied, so in this case everything but productName=

This example could be for any combination of input.

Is there a way to do this?

Thanks.

    $name = $_POST['n'];
    $cat = $_POST['c'];
    $price = $_POST['p'];

if( !($name) )
{
    $name = some character to select all?
}


$sql = "SELECT * FROM products WHERE productCategory='$cat' and   
productName='$name' and productPrice='$price' ";

EDIT
Solution does not have to protect from attacks. Specifically looking at the dynamic part of it.

Greg McNulty
  • 1,476
  • 5
  • 28
  • 50
  • Are you aware the code you posted, as it is, is highly insecure and wide open to attacks? If not, please take 5 minutes to read: http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php – Mahn Jun 25 '12 at 03:10

1 Answers1

2

something like

$where_array = array();

if( isset($_POST['n']) )$where_array[] = "productName = '{$_POST['n']}'";
if( isset($_POST['c']) )$where_array[] = "productCategory '{$_POST['c']}'";
if( isset($_POST['p']) )$where_array[] = "productPrice = '{$_POST['p']}'";

    $where_stmt = implode( ' and ', $where_array  );
    if( $where_stmt )  
    {
    $sql = "SELECT * FROM products WHERE $where_stmt ";
//run query
    }
Sean Johnson
  • 5,567
  • 2
  • 17
  • 22
Nick Maroulis
  • 486
  • 9
  • 28
  • nice, let me give that a try. – Greg McNulty Jun 25 '12 at 03:08
  • 1
    This is a nice solution, but the variables plugged in really should be mysql_real_escape_string()'d, otherwise it's susceptible to mysql injections. I've also added quotes to wrap the variables plugged in, it won't function as you've posted. – Sean Johnson Jun 25 '12 at 03:11
  • @marabutt: the number works but I get an error in the syntax for the strings. should the {} work for strings? – Greg McNulty Jun 25 '12 at 03:45
  • can you paste var_dump( $_POST ); – Nick Maroulis Jun 25 '12 at 03:48
  • @Sean Johnson: the single quotes did the trick. Thank you all. Very helpful! – Greg McNulty Jun 25 '12 at 04:26
  • 1
    Again, I can't stress enough that the variables need to be escaped before being plugged into the query. Never plug user data into a query string without mysql_real_escape_string()ing it or you leave your application open to injections. Check out [MySQLi](http://php.net/manual/en/book.mysqli.php) and some of its practices as an alternate, secure way of executing your MySQL. – Sean Johnson Jun 25 '12 at 04:30