1

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.

3 Answers 3

5

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

Comments

2

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

Comments

0

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)

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.