0
<?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}

任何帮助,将不胜感激。谢谢。

4

1 回答 1

1

您不会对find_email. find_email你的类在被调用时不会更新它自己的属性。相反,它返回一个带有emailandpassword属性集的类的新实例,因此您需要捕获返回值并对其进行编码。

改成:

$result = new User();
$user = $result->find_email($_GET['email'], $_GET['password']);
echo json_encode($user);

旁注:看看SOLIDDependency Injection。DI 比拥有global $Database.

于 2013-07-04T07:53:36.640 回答