Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I have an array lets say: Array ( [0] => 9 [1] => 7 [2] => 8 )

I want to SELECT from a table (users) all phone numbers where userID matches one from the array (if there is a phone number listed).

I want to do this without selecting all of the users from the database and only those that match that of the array and with actual phone numbers, should I do this in a loop?

Typically when I am doing an UPDATE, I do them within a foreach loop. Like so:

foreach($userArr as $user) {
            $pid = $user;
            if(!$statement->execute()) {
                    throw new Exception($statement->error, $statement->errno);
            }
    }
$statement->close();

Can we do SELECT like that as well?

Thanks in advance for any advice.

share|improve this question
up vote 4 down vote accepted

If you want to select all these users, just do the follow:

$idList = implode(',', $yourArray);
$sql = "SELECT * FROM users WHERE id IN($idList)";
// execute this $sql query
share|improve this answer

Try this:

    <?php

    $array = array(9, 7, 8);

    $query = "SELECT * FROM mytable WHERE id = ";

    $condition = implode(' OR id = ', $array);

    $query .= $condition;

    echo $query;
?>

Output:

SELECT * FROM mytable WHERE id = 9 OR id = 7 OR id = 8
share|improve this answer

You should do the following:

  1. Build a string to express the userid seperated by comma. - Loop will be needed. i.e id1, id2, id3
  2. Build the query string to search for them.

Example:

SELECT * FROM `Users` WHERE id IN (id1, id2, id3)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.