0

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.

5
  • 4
    Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial. Commented Mar 18, 2013 at 17:32
  • 1
    user=1 and user=2 ? do you mean OR Commented Mar 18, 2013 at 17:32
  • Can user be equal to both '1' and 'arr_1'? Perhaps you just need to use IN here, like SELECT * FROM users WHERE user IN (1, 'arr_1', ...)? Commented Mar 18, 2013 at 17:33
  • 1
    what is $arr++ if $arr='arr_1'; Commented Mar 18, 2013 at 17:33
  • cant put foreach in mysql - but you can do user IN ('arr_1','arr_2','arr_3') BTW this does OR Commented Mar 18, 2013 at 17:40

2 Answers 2

2

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";
?>
Sign up to request clarification or add additional context in comments.

7 Comments

You still need to replace the . with a ; and I would say you have to add another whitespace before or after each iteration.
@insertusernamehere: didnt notice that, and i changed accordingly
It's a bit like back in school: "Find all mistakes in this code. Solve it with pen and paper.". :)
Still this query is likely to not return anything as AND is used which will fail for sure as no column will be equal to all of the values.
I just inserted OR insted of AND and change it a bit and its working perfect :) Thanks :)
|
0

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";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.