1

I have an Array $f_array whose values are loaded by while loops and SQL Query.

I want to use this array name in a SQL Query.

$sql="SELECT * FROM comment WHERE uname IN ($f_array) ORDER BY ID DESC";

This is what my array looks like after the data is loaded,

array(4) { 
    [0]=> string(8) "wisahmed" 
    [1]=> string(10) "test_user1" 
    [2]=> string(10) "test_user2" 
    [3]=> string(10) "test_user3" 
}

Could someone tell me how can I load this array into the above MySQL Query.

3
  • PS: Im only a beginner. I'm not sure what to search for. Commented Jan 23, 2018 at 7:49
  • Show your second SQL query Commented Jan 23, 2018 at 7:50
  • So the source of $f_array is itself a query? If so, you're probably better of using a join. Commented Jan 23, 2018 at 8:02

3 Answers 3

3

You need to build a quoted, comma separated list. This is easily accomplished from an array source with implode:

$imploded = implode("','", $f_array)

This would render:

wisahmed','test_user1','test_user2','test_user3

So wrapping that in single quotes and putting it in your existing query results in proper formatting:

$sql="SELECT * FROM comment WHERE uname IN ('{$imploded}') ORDER BY ID DESC";

Becoming:

SELECT * FROM comment WHERE uname IN ('wisahmed','test_user1','test_user2','test_user3') ORDER BY ID DESC
Sign up to request clarification or add additional context in comments.

Comments

1

First convert array to string

$array = ["wisahmed", "test_user1", "test_user2", "test_user3"];
$users = implode(",", $array);

Update your query

$sql="SELECT * FROM comment WHERE uname IN($users) ORDER BY ID DESC";

Comments

0

you can't use the array directly, you have to transform it to string first so try the following:

$users = "'".implode("','",$f_array)."'";

and then the query should be

$sql="SELECT * FROM comment WHERE uname IN ($users) ORDER BY ID DESC";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.