Jump to content

php array in sql statement


russthebarber

Recommended Posts

I have a php function that takes two arguments which it uses to make an sql statement:

 

public static function advanced_search($city, $state) {
return self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE addressTown='{$city}' AND state='{$state}' AND area='1'");
}

 

My problem is I would like to insert a third variable (actually an array) that the function takes. This array will contain field names that I want to check in the statement to see which of them are equal to "1". The problem is this array might have 1 field name or anything up to 8 field names. I am not sure how to break out of the sql statement to loop through this array. Here is the statement with 3 field names that might help describe what I am trying to do:

 

public static function advanced_search($city, $state, $myFieldNameArray) {
return self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE addressTown='{$city}' AND state='{$state}' AND ".$myFieldNameArray[0]."='1' AND ".$myFieldNameArray[1]."='1' AND ".$myFieldNameArray[2]."='1'");
}

 

I hope that's clear enough. What I am struggling with is the syntax for how to break out of the statement and run through a for loop inserting something like this for each field name in the array

 

AND ".$myFieldNameArray[$i]."='1' "

 

Link to comment
Share on other sites

Ok, I think I have a solution. Maybe it can help somebody else or maybe someone has a better one...

 

public static function advanced_search_all($city, $state, $myFieldNameArray) {
        $sql = "SELECT * FROM ".self::$table_name." WHERE addressTown='{$city}' AND state='{$state}'";
for ($i=0; $i<count($myFieldNameArray); $i++){
	$sql .=" AND ".$myFieldNameArray[$i]."='1'";
}
return self::find_by_sql($sql);
}

Link to comment
Share on other sites

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.