Reputation: 25
Im trying to fill query with array. As I know I can display array with function foreach();
but im not able to put it in mysql query
Im trying to do something like this:
<?php
$arr = array("arr_1", "arr_2", "arr_3", "arr_4");
$query = mysql_query("SELECT * FROM users WHERE user = '1'".
foreach($arr as $arr) {
echo "AND user = '".$arr++."'";
}
." ORDER BY id";
?>
Script have to display this as:$query = mysql_query("SELECT * FROM users WHERE user = '1' AND user = 'arr_1' AND user = 'arr_2' AND user = 'arr_3' AND user = 'arr_4'");
But this doesnt work becouse you cant put foreach()
in mysql_query();
.
So what I need is script that do the same thing ( display array in query string )
Thanks.
Upvotes: 0
Views: 380
Reputation: 2693
Not the best solution, but an alternative:
$arr = array("arr_1", "arr_2", "arr_3", "arr_4");
$arr_string="'".implode("','", $arr)."'"; // surround values in quotes
$query = mysql_query("SELECT * FROM users WHERE user IN (".$arr_string.") ORDER BY id";
Upvotes: 0
Reputation: 6192
if you want to add multiple conditions from array, do concatenation instead of echo
<?php
$arr = array("arr_1", "arr_2", "arr_3", "arr_4");
$query = mysql_query("SELECT * FROM users WHERE user = '1'";
foreach($arr as $id) {
$query .= "AND user = '".$id."'";
}
$query .= " ORDER BY id";
?>
Upvotes: 2