Jump to content

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.

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())

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.