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
https://forums.phpfreaks.com/topic/262227-php-array-in-sql-statement/
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);
}

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.