russthebarber Posted May 7, 2012 Share Posted May 7, 2012 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 More sharing options...
russthebarber Posted May 7, 2012 Author Share Posted May 7, 2012 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 https://forums.phpfreaks.com/topic/262227-php-array-in-sql-statement/#findComment-1343829 Share on other sites More sharing options...
Mahngiel Posted May 7, 2012 Share Posted May 7, 2012 use php's serialize() on the array to turn it into a stored representation of the array. when you recall the data from the table, unserialize() it. Link to comment https://forums.phpfreaks.com/topic/262227-php-array-in-sql-statement/#findComment-1343832 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.