Dyanamic Select Query

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ghjk
    Contributor
    • Jan 2008
    • 250

    Dyanamic Select Query

    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,pri ce etc..

    Code:
    SELECT * FROM vehicles WHERE vehicleMake='$make' AND vehiclemodel='$model
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    You can use PHP to build a dynamic string using if then else statements and then pass that to MySQL.

    Comment

    • ghjk
      Contributor
      • Jan 2008
      • 250

      #3
      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..
      Code:
      if(isset($_GET['S'])==5){
      
      	$make=$_GET['make'];
      	$model=$_GET['model'];
      	$type=$_GET['type'];
      	$fuel=$_GET['fuel'];
      	$color=$_GET['color'];
      	
      
      	$query = "SELECT * FROM vehicles where";
      	if($make){
      	$query .= " vehicleMake = '$make'";
      	}
      	if($model!=" ")
      	{
      	$query .= " and vehicleModel = '$model'";
      	}
      	if($type!= " "){
      	$query .= " and vehicleType = '$type'";
      	}
      if($fuel!= " "){
      	$query .= " and vehicleFuel = '$fuel'";
      	}
      	
      	$query.=';';
      	
      
      $result = mysql_query($query)or die(mysql_error());
      
      echo "<table width=100% align=center>";
      	echo "&nbsp;&nbsp;<tr height=20 bgcolor=#C0C0C0><td align=center>Vehicle Make</td><td align=center>Vehicle Model</td><td>SELECT</td></tr>";
      
      	while($row = mysql_fetch_array($result))
      	{
      		foreach( $row AS $key => $val ){
      		$$key = stripslashes( $val );
      		}
      				
      	echo "<tr class=normalText>";
       
      	echo "<td> $vehicleMake</td>";
      	echo "<td> $vehicleModel</td>";
      
      	echo  "<td><a href='javascript:void(0);' onclick=\"LookupVehicle('$vehicleType','$vehicleMake'); return false;\">Select</a></td>";
      			echo "</tr>";
      	}
      	echo "</table>";
      	
      	}

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        You should output the sql string it's trying to use to make sure it's correct.

        Comment

        Working...