34

I want to know is this practically possible in sql(using php as server-side), where in you have an array of values(numbers), and you try to retrieve data based on values inside that array..

I have a sql table:

posts(
    id int(11) primary key,
    posts varchar(140),
    user_id int(11) foreign key
);

I write a query now to retrieve 'posts':

$query="SELECT * FROM posts WHERE user_id=(**Array of select user_id's**)";

Is there any sql in-built function to check values inside an array? or should I be using PHP for this?

I am actually trying to implement the twitter model of showing posts of people whom we follow.

1
  • 3
    SELECT * FROM posts WHERE user_id IN (1,2,3); Commented Nov 25, 2011 at 13:59

4 Answers 4

46

Yes, this is easily possible. You need to look at MySQL's IN function

Your query would be something like

SELECT * FROM posts WHERE user_id IN (1,2,3,4,5,6)

You can build the bit in between the parentheses in PHP using implode()

Sign up to request clarification or add additional context in comments.

Comments

21

SQL can't parse PHP arrays. Try this:

$query="SELECT * FROM posts WHERE user_id IN ({implode(',', $userIDarray)})";

5 Comments

Just be careful that the array values have been sanitized for SQL injection.
Of course... I for myself would use prepared statements, but that's not the question ;)
wat sanitary functions needed to sanitise an array?
in this case only integer values are permitted. So you need to check for integer values in each array element. If you don't generate this array from user inputs (or the values of the arrays do not contain any) you can skip this.
you forgot an ) after the variable
3

Take a look at this page : WHERE ... IN. You can use the IN operator to check if a certain value exists within an list of values.

Comments

-1

Yea you will have to you use following syntax

SELECT 'value'
 IN (array)

1 Comment

stop linking to your website like this.

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.