By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,960 Members | 987 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,960 IT Pros & Developers. It's quick & easy.

Dyanamic Select Query

100+
P: 250
In my web application I'm using php and mysql. I want to create sql query to search function. There are many search fields. Sometimes user select only one field and some times two and sometimes many. How can I write that kind of query. This is my query.Other options are make, color,model,price etc..

Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM vehicles WHERE vehicleMake='$make' AND vehiclemodel='$model
  2.  
Sep 7 '11 #1
Share this Question
Share on Google+
3 Replies


Rabbit
Expert Mod 10K+
P: 12,347
You can use PHP to build a dynamic string using if then else statements and then pass that to MySQL.
Sep 7 '11 #2

100+
P: 250
This is my code. When I select only vehicle type.It will get only one record. I couldn't understand where I goes wrong. Please help me..
Expand|Select|Wrap|Line Numbers
  1. if(isset($_GET['S'])==5){
  2.  
  3.     $make=$_GET['make'];
  4.     $model=$_GET['model'];
  5.     $type=$_GET['type'];
  6.     $fuel=$_GET['fuel'];
  7.     $color=$_GET['color'];
  8.  
  9.  
  10.     $query = "SELECT * FROM vehicles where";
  11.     if($make){
  12.     $query .= " vehicleMake = '$make'";
  13.     }
  14.     if($model!=" ")
  15.     {
  16.     $query .= " and vehicleModel = '$model'";
  17.     }
  18.     if($type!= " "){
  19.     $query .= " and vehicleType = '$type'";
  20.     }
  21. if($fuel!= " "){
  22.     $query .= " and vehicleFuel = '$fuel'";
  23.     }
  24.  
  25.     $query.=';';
  26.  
  27.  
  28. $result = mysql_query($query)or die(mysql_error());
  29.  
  30. echo "<table width=100% align=center>";
  31.     echo "&nbsp;&nbsp;<tr height=20 bgcolor=#C0C0C0><td align=center>Vehicle Make</td><td align=center>Vehicle Model</td><td>SELECT</td></tr>";
  32.  
  33.     while($row = mysql_fetch_array($result))
  34.     {
  35.         foreach( $row AS $key => $val ){
  36.         $$key = stripslashes( $val );
  37.         }
  38.  
  39.     echo "<tr class=normalText>";
  40.  
  41.     echo "<td> $vehicleMake</td>";
  42.     echo "<td> $vehicleModel</td>";
  43.  
  44.     echo  "<td><a href='javascript:void(0);' onclick=\"LookupVehicle('$vehicleType','$vehicleMake'); return false;\">Select</a></td>";
  45.             echo "</tr>";
  46.     }
  47.     echo "</table>";
  48.  
  49.     }
  50.  
Sep 9 '11 #3

Rabbit
Expert Mod 10K+
P: 12,347
You should output the sql string it's trying to use to make sure it's correct.
Sep 9 '11 #4

Post your reply

Sign in to post your reply or Sign up for a free account.