我想要檢索的所有用戶在我的數據庫,並把它們與兩個元素的數組;一個包含一個包含所有用戶標識的數組,另一個包含所有用戶名的數組。但是,下面的代碼不適用於此目的。它的作用是將第一個用戶放入$ field1(第一個用戶的用戶標識)和$ field2(第一個用戶的用戶名)中。檢索所有的用戶(用戶ID和用戶名)
我需要如何解決這個問題的幫助。
基本上,我要的是實現以下目標:
$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
);
從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;
}
}
從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;
}
db表看起來像這樣: userId |用戶名|密碼
什麼'$ field1'和'$ field2'包含? – haynar
@haynar:它們包含在db表中的第一用戶的第一用戶ID($ FIELD1)和用戶名($域2)。 – holyredbeard