【发布时间】:2018-01-05 07:50:19
【问题描述】:
我正在尝试使用 OO-PHP 从数据库中检索数据 这是我的代码
用户.php
<?php
require_once("init.php");
class User{
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public static function find_all_users(){
return self::find_this_query("SELECT * FROM users");
}
public static function find_user_by_id($user_id){
global $database;
/* $result_set = $database->query("SELECT * FROM users WHERE id=$user_id LIMIT 1");*/
$result_set = self::find_this_query("SELECT * FROM users WHERE id=$user_id LIMIT 1");
$found_user = mysqli_fetch_array($result_set);
return $found_user;
}
public static function find_this_query($sql){
global $database;
$result_set = $database->query($sql);
$the_object_array = array();
while($row = mysqli_fetch_array($result_set)){
$the_object_array[] = self::instantation($row);
}
return $result_set;
}
public static function instantation($the_record){
$the_object = new self;
/* $the_object->id = $found_user['id'];
$the_object->username = $found_user['username'];
$the_object->password = $found_user['password'];
$the_object->first_name = $found_user['first_name'];
$the_object->last_name = $found_user['last_name'];*/
foreach($the_record as $the_attribute => $value){
if($the_object->has_the_attribute($the_attribute)){
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
private function has_the_attribute($the_attribute){
$object_properties = get_object_vars($this);
return array_key_exists($the_attribute, $object_properties);
}
}
?>
数据库.php
public function query($sql){
/*$result = mysqli_query($this->connection,$sql);*/
$result = $this->connection->query($sql);
$this->confirm_query($result);
return $result;
}
index.php
$users = User::find_all_users();
foreach($users as $user){
echo $user->username;
}
尝试从数据库中检索用户时出现错误
试图获取非对象的属性
【问题讨论】:
-
将您的用户输出显示为 print_r($user)
-
可能是你的查询有错误或与sql连接请检查sql是否连接并尝试在sql中执行查询