Jump to content

Recommended Posts

I need help with a select statement. My statement is

 

$result = mysql_query("SELECT * FROM properties WHERE city = '$city' AND beds LIKE '%$beds%' AND baths LIKE '%$baths%' OR state = '$state' AND beds LIKE '%$beds%' AND baths LIKE '%$baths%' OR  zip = '$zip' AND beds LIKE '%$beds%' AND baths LIKE '%$baths%'  ORDER BY date DESC LIMIT 0,8");

 

What I am trying to do is select rows by state, city or zip and those results are further narrowed by how many bedrooms and baths the user selects. The problem If the user just wants out a city or state and ignores the beds and baths, it doesnt return any results.  I want it to.  Any suggestions?

Link to comment
https://forums.phpfreaks.com/topic/54772-solved-select-statement-help/
Share on other sites

perhaps a long winded way but a possible stop gap would be to have a seperate select statement that is executed if only the  city is entered...so along the lines of if city is not empty AND beds OR baths are empty, just select from the DB where city matches the user input

 

 

You need to create your query dynamically based upon the user input. Plus, that query is inefficient as you are repeatedly restating the clauses for beds and baths. You just need to put the locations within parenthetical operators.

 

Here is an example, but I would add a lot more error handling and validation of the variables.

 

<?php

$query = "SELECT *
         FROM properties
         WHERE (city = '$city' OR state = '$state' OR zip = '$zip') ";

$query .= ($beds!='')? "AND beds LIKE '%$beds%' "  : '' ;
$query .= ($baths!='')? "AND baths LIKE '%$baths%' " : '' ;

$query .= "ORDER BY date DESC LIMIT 0,8";

$result = mysql_query($query) or DIE (mysql_error());

?>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.   Restore formatting

  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.

×
×
  • 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.