Reputation: 3
I'm trying to query with a php list, I'm not even sure if it is possible but hopefully you can give some advice/assistance on the matter.
I get a zip list from another function that contains a lot of zip codes, and I want to use that list to narrow down a search.
Notice: Array to string conversion in C:\wamp\www
This is where I get the array to string error
. JOIN zip_list zl ON r.zip_code IN ('$zip_list') "
I know it works perfectly with replacing $zip_list with ('2150','2165') for example but the list will be rather long so I can't just put $zip_list[$i].
I've tried some conversion with $trimZip and $test but it always yields the same error.
for($i=0; $i<count($zip_list); $i++){
array_push($trimZip, "'".$zip_list[$i]."',");
$i = $i+1;
}
for($i = 0; $i<count($trimZip); $i++){
$test[$i] = $trimZip[$i];
}
Is there a good way to do this or am I even looking at it the right way ? Better/easier angles are welcome too!
Upvotes: 0
Views: 2739
Reputation: 3
$sql_string = implode(', ', $zip_list);
Implode did the trick, thanks for the help
Upvotes: 0
Reputation: 23892
This
$sql_string = implode(', ', $zip_list);
should do it.
Sample:
$zip_list = array(1, 2);
$sql_string = implode(', ', $zip_list);
echo $sql_string;
Output:
1, 2
Demo: https://eval.in/483839
This presumes you validated the data in $zip_list
when assigning it. Variables being used directly in SQL isn't good practice. You should really look into parameterized queries.
I'd do:
$zip_list = array(1, 2);
foreach($zip_list as $param) {
$placeholders[] = '?';
}
$sql_string = implode(', ', $placeholders);
echo $sql_string;
Then use $sql_string
in the prepare and $zip_list
in the execute.
Dependent on your driver:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/manual/en/pdo.prepared-statements.php
Upvotes: 1