Jump to content

having a for loop inside a mysql SELECT statement


micmola

Recommended Posts

An example of having a for loop inside a mysql SELECT statement is below:

 

$query = "SELECT * FROM car WHERE offer_type = '" . $transaction_type . 

                       for ($x=0; x<count($sentence_array); $x++) {
                 "' AND car_name = '" . $sentence_array[$x] . 
	  "' OR car_color = '" . $sentence_array[$x] . 
	  "' OR car_seats = '" . $sentence_array[$x] . 
       }

"'";

 

The sentence_array contains one word per element. Please someone help me on this.

Link to comment
Share on other sites

You want to build a query string using a for loop, not actually run a for loop inside a SELECT statement.

 

Actually, you can do it without a for loop, just use implode(). Something like this should work:

$query = "SELECT * FROM car WHERE offer_type = '" . $transaction_type . " AND ";
$query .= "( car_name IN ('" . implode("' OR '", $sentence_array) . "')";
$query .= " OR car_color IN ('" . implode("' OR '", $sentence_array) . "')";
$query .= " OR car_seats IN ('" . implode("' OR '", $sentence_array) . "')";
$query .= ')';

 

Note: Untested. (I don't have an environment here to test with).

Note: Make sure you sanitize those inputs if they are coming from a user. (see mysql_real_escape_string())

Link to comment
Share on other sites

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.