0

I there a way I can return several rows by using a foreach in PHP ?

Example:

I want to loop into the Users table and I have this list of Users id's.

$users = "1,2,3";

foreach ($users as $user) {
    SELECT * FROM Users where id = :user;
}

But here, I need the query the db 3 times.

Is there a way to make it in one query ?

Thanks.

1
  • 2
    I'd retrieve the users first, so SELECT * FROM Users WHERE id IN (1,2,3) then use your foreach to loop the result Commented Mar 22, 2017 at 14:55

2 Answers 2

1

using where in mysql statement you can use by single query

SELECT * FROM Users where id in ( $users);

like

SELECT * FROM Users WHERE id IN (1,2,3);
Sign up to request clarification or add additional context in comments.

Comments

0

Try:

function getUsers() {
        $sql = "SELECT
                  * FROM Users";
        //echo $sql;
        //$dbConn = new PDO('blah blah');
        $result = $dbConn->query($sql);
        //this can be output if no user exists, 
        $user= array();            
            while ($row = $result->fetch_array()) {
                $users= array(
                //store the id's as an array here
                    'id' => $row['id'],                        
                );
                array_push($user, $users);
            }
        }
        return $user;
    }

//Add prepared statements here to make prevent SQL injection

Comments

Your Answer

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