Jump to content

[SOLVED] Search form MySQL problem


stuieb

Recommended Posts

Hi,

 

I have a search form on a page that has three select fields.

 

make

 

location

 

price

 

Each is dynamicly generated from information in the database.

 

The form goes to a results page (GET) and displays the results.

 

The problem I am having is with the MySQL SELECT on the results page. Basicly I want the user to be able to search for all records from 'make' from within the table, or all records from 'location' or all records from 'price' or by a combination of all three. Make, location and price are all cols in a table bye the way.

 

MySQL Version 4.1

 

 

Please help!

 

Stu.

 

Link to comment
https://forums.phpfreaks.com/topic/100367-solved-search-form-mysql-problem/
Share on other sites

This is one way:

 

<?php
$keys = array('make','location','price');
$qry = "SELECT * FROM products";
$where = array();
foreach($keys as $key){
  if(strlen($_GET[$key]))
    $where[] = "`{$key}` = '{$_GET[$key]}'"
}
if(count($where))
  $qry .= " WHERE ".implode(' AND ',$where);

$result = mysql_query($qry);
//etc

?>

Good  solution>>

This is one way:

 

<?php
$keys = array('make','location','price');
$qry = "SELECT * FROM products";
$where = array();
foreach($keys as $key){
  if(strlen($_GET[$key]))
    $where[] = "`{$key}` = '{$_GET[$key]}'"
}
if(count($where))
  $qry .= " WHERE ".implode(' AND ',$where);

$result = mysql_query($qry);
//etc

?>

Stu: The other solutions would just have different styles of coding. This is pretty sleek. 

Same code with some comments. I was also missing a semi-colon:

 

<?php
$keys = array('make','location','price'); //List of columns to filter on
$qry = "SELECT * FROM products"; //Start the SQL statement
$where = array(); //Initiate array to store the WHERE items
foreach($keys as $key){ //Loop over each filter item
  if(strlen($_GET[$key])) //Check to see if the filter item is set
    $where[] = "`{$key}` = '{$_GET[$key]}'"; //Add filter item to WHERE array
}
if(count($where)) //If there are any WHERE pieces
  $qry .= " WHERE ".implode(' AND ',$where); //Add them to the query here

$result = mysql_query($qry);
//the rest is standard MySQL calls

?>

Same thing a bit differently

 

 


$sql = "SELECT * FROM products"; 

$sqlWhere = '';
$sqlAnd = '';

if (!empty($_GET['make']))
{
$sqlWhere.= " make ='".$_GET['make']."'"; 
$sqlAnd = " And ";
}

if (!empty($_GET['price']))
{
$sqlWhere.= $sqlAnd." price ='".$_GET['price']."'"; 
$sqlAnd = " And ";

}
if (!empty($_GET['location']))
{
$sqlWhere.= $sqlAnd." location ='".$_GET['location']."'"; 

}


if (!empty($sqlWhere))
{
$sql.=" WHERE ".$sqlWhere;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.