Jump to content
Sign in to follow this  
adam.jones2

Handling Empty queries

Recommended Posts

I have a PHP/SQL Query $query = "SELECT * FROM site_cars WHERE car_Make = $Make AND car_price BETWEEN $Min_Price AND $Max_Price"; If the $Min_Price AND $Max_Price is equal to "" the query fails to run. is there a way around this?

Edited by adam.jones2

Share this post


Link to post
Share on other sites

Don't run the query if the values are empty. You're supposed to test that all the values are what they should be before the query.

Share this post


Link to post
Share on other sites

Check the input, and only add the WHERE when input is present, e.g.

$query = "SELECT * FROM site_cars";$filters = array();if (!empty($Make)) { $filters[] = "car_Make = $Make";}if (!empty($Min_Price) && !empty($Max_Price)) { $filters[] = "car_price BETWEEN $Min_Price AND $Max_Price";}if (!empty($filters)) {$query .= ' WHERE ' . implode(' AND ', $filters);}

Share this post


Link to post
Share on other sites

Iv gone with this approch. any ideas why it dont work?

$Make = $_POST['make'];$Min_Price = $_POST['pf'];$Max_Price = $_POST['pt'];//check if there was tried a searchif ($_POST["make"] ||$_POST["pf"] || $_POST["pt"]) {//ok, this was a search$query =  " car_make= " . $_POST["make"] . "";if ($Min_Price || $Max_Price)$query= " (car_price >= " . (int) $_POST["pf"] . "" . ($_POST["pt"] ? " AND car_price <= "  . (int) $_POST["pt"] . "" : "")  . ") ";// Search Array    if (is_array($query)) {    $cars = mysql_query("SELECT * FROM site_cars WHERE" . implode(" AND " , $query) . " ORDER BY car_price desc");    } else die('<p class="error">######.</p>');    $numresults=mysql_query ($query);    if(!$numresults) {    echo mysql_error();	 exit;}

Edited by adam.jones2

Share this post


Link to post
Share on other sites

You're missing a bracket here:

if ($Min_Price || $Max_Price)$query

should be

if ($Min_Price || $Max_Price) {$query

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...