holyredbeard
holyredbeard

Reputation: 21278

Retrieve all users (userId and usernames)

I want to retrieve all the users in my db and put them in an array with two elements; one containing an array with all the user id's and the other an array with all the usernames. However, the code below doesn't work for this purpose. What it does is putting the first user in the db in $field1(the user id of the first user) and $field2(the username of the first user).

I need help with how to solve this problem.

Basically, what I want is to achieve the following:

$userIds = array(1, 2, 3, 4, 5);    // The id's from all users in an array
$userNames = array("Nisse", "Kalle", "Svenne", "Jonna", "Linda");    // The usernames of all the users in an array

// The arrays with user id's and usernames should be put in a new array that's returned from the function.
$users = array(
  [0] => $userIds,
  [1] => $userNames
);

from UserHandler.php:

class UserHandler {

    private $m_db = null;

    public function __construct(Database $db) {
        $this->m_db = $db;
    }

    public function GetAllUsers() {

        $userArray = array();

        $query = 'SELECT * FROM Users'; 

        $stmt = $this->m_db->Prepare($query);

        $userArray = $this->m_db->GetUsers($stmt);

        return $userArray;
    }
}

from Database.php:

public function GetUsers(\mysqli_stmt $stmt) {
        $userArray = array();

        if ($stmt === FALSE) {
                throw new \Exception($this->mysqli->error);
        }

        //execute the statement
        if ($stmt->execute() == FALSE) {
                throw new \Exception($this->mysqli->error);
        }
        $ret = 0;

        if ($stmt->bind_result($field1, $field2, $field3) == FALSE) {
            throw new \Exception($this->mysqli->error);
        }

        $stmt->fetch();

        $stmt->Close();

        echo $field1 // "1";    <- userid of the first user in db table
        echo $field2 // "Kalle"    <- username of the first user in the db table

        $userArray[] = $field1;    // An array with all the user id's
        $userArray[] = $field2;    // An array with all the usernames

        return $userArray;
}

The db table looks like this: userId | username | password

Upvotes: 1

Views: 836

Answers (1)

haynar
haynar

Reputation: 6040

doing $stmt->fetch() only once you're fetching only the first row from the result table, so you need a loop over the result table:

public function GetUsers(\mysqli_stmt $stmt) {
    $userArray = array(
        0 => array(),
        1 => array()
    );

    // the rest of code is the same here

    // replace the line $stmt->fetch() with this block
    while ($stmt->fetch()) {
        array_push($userArray[0], $field1);
        array_push($userArray[1], $field2);
    }

    // remove these lines
    /*
    $userArray[] = $field1;
    $userArray[] = $field2;
    */

    return $userArray
}

Upvotes: 2

Related Questions