我想将数组值存储为对象属性。我正在以mysqli为例,但我想改用PDO。
我有一个用户类别:
class User {
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public static function find_all_users(){
global $database;
$result_set = $database->query($sql);
return $result_set;
} //end method
} //end User class
我已使用以下数据库类连接到我的数据库。 注意:常数DB_SERVER等已在其他位置定义并包含在文件中
class Database{
public $connection;
function __construct(){
$this->open_db_connection();
}//end of constructor
public function open_db_connection(){
try{
$this->connection = new PDO('mysql:host='. DB_SERVER .';dbname='. DB_NAME, DB_USER, DB_PASSWORD);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'Server Error: ' . $e->getCode(;
}//end catch block
}//end of method
public function query($sql){
$stmt = $this->connection->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
} //end query method
$database = new Database();
我想从User类创建一个对象,并使用该类的属性访问我的数据。
$user = new User();
$user->id = $result_set['id'];
$user->username = $result_set['username'];
$user->password = $result_set['password'];
$user->first_name = $result_set['first_name'];
$user->last_name = $result_set['last_name'];
echo $user->id;
在mysqli中,将通过以下操作完成 :
public static function find_all_users(){
global $database;
$result_set = $database->query($sql);
mysqli_fetch_array($result_set);
return $result_set;
} //end method
我得到的错误是 “未定义的索引:ID” “未定义的索引:用户名” “未定义的索引:密码” “未定义的索引:first_name” “未定义的索引:last_name”
我认为我的错误来自fetchAll(PDO :: FETCH_ASSOC)。我应该从echo语句中获取一个值。回声$ user-> id;
有什么更好的获取方法与PDO的mysqli_fetch_array相似?
下面是当我print_r $ result_set时:
答案 0 :(得分:-1)
fetchAll()
返回一个二维数组。您需要遍历元素:
$all_users = array();
foreach ($result_set as $result) {
$user = new User();
$user->id = $result['id'];
$user->username = $result['username'];
$user->password = $result['password'];
$user->first_name = $result['first_name'];
$user->last_name = $result['last_name'];
$all_users[] = $user;
echo $user->id;
}