<?php
require_once (realpath(dirname(__FILE__) . '/../includes/database.php'));
class User {
public $email;
public $password;
public function find_email($email, $password) {
global $database;
$pswd = substr(md5($password), 0, 25);
$results_array = self::find_by_sql("SELECT * FROM tbl_users where email_id='".$email."' AND password='".$pswd."'");
return !empty($results_array)? array_shift($results_array) : false;
}
public static function find_by_sql($sql){
global $database;
$results = $database -> query($sql);
$object_array = array();
while($row = $database -> fetch_array($results)){
$object_array[] = self::instantiate($row);
}
return $object_array;
}
public static function instantiate($row) {
$event = new self;
foreach($row as $attribute => $value) {
if($event -> has_attribute($attribute)) {
$event -> $attribute = $value;
}
}
return $event;
}
private function has_attribute($attribute) {
$object_vars = get_object_vars($this);
return array_key_exists($attribute, $object_vars);
}
}
if (isset($_GET['email']) && isset($_GET['password'])) {
$result = new User();
$result->find_email($_GET['email'], $_GET['password']);
echo json_encode($result);
}
?>
这是login.php,它应该打印出所需用户的json,但每当我尝试获取json时,都会返回。
{"email":null,"password":null}
任何帮助将不胜感激。感谢。
答案 0 :(得分:1)
您对find_email
的结果不做任何处理。调用find_email
时,您的类不会更新它自己的属性。相反,它返回一个设置了email
和password
属性的类的新实例,因此您需要捕获返回值并对其进行编码。
更改为:
$result = new User();
$user = $result->find_email($_GET['email'], $_GET['password']);
echo json_encode($user);
旁注:请查看SOLID和Dependency Injection。 DI优先于global $Database
。