PHP& MySQL OOP - 为什么我没有得到结果?

时间:2016-02-07 18:23:51

标签: php mysql class oop object

我不确定为什么浏览器中没有返回/输出全名。有人可以帮忙吗?我有一个类文件,其中包含特定类,仅用于更有条理的文件结构。数据库类包含了与数据库相关的所有当前方法,而用户类包含了用户的方法,我从用户类的数据库中调用了一些方法,但我确信方法和属性的范围是设置正确吗?

classes.php:

include 'database.php';
include 'user.php';
$user = User::getUserId(1);
echo $user->getName();

database.php中

<?php
require_once("../core/config.php");

class Database {
    private $connection;

    function __construct() {
        $this->connect();
    }

    public function connect() {
        $this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
        if(mysqli_connect_errno()) {
            die("Database connection failed: " . 
               mysqli_connect_error() . 
               " (" . mysqli_connect_errno() . ")"
            );
        }
    }

    public function disconnect() {
        if(isset($this->connection)) {
            mysqli_close($this->connection);
            unset($this->connection);
        }
    }

    public function query($sql) {
        $result = mysqli_query($this->connection, $sql);
        if (!$result) {
            die("Database query failed.");
        } 
        return $result;
    }

    public function prepare($data) {
        $escString = mysqli_real_escape_string($this->connection, $data);
        return $escString;
    }

    public function fetchArray($results) {
        return mysqli_fetch_array($results);
    }
}

$db = new Database();

?>

user.php的

<?php

class User {

    public $userId;
    public $username;
    public $password;
    public $email;
    public $firstname;
    public $lastname;
    public $access;
    public $active;

    public static function getUsers() {
        return self::getBySQL("SELECT * FROM users");
    }

    public static function getUserId($id=0) {
        global $db;
        $result = self::getBySQL("SELECT * FROM users WHERE userId={$id} LIMIT 1");
        return !empty($result) ? array_shift($result) : false;
    }

    public static function getBySQL($sql) {
        global $db;
        $result = $db->query($sql);
        $objArray = array();
        while ($row = $db->fetchArray($result)) {
            $objArray[] = self::instantiate($row);
        }
        return $objArray;
    }

    public function getName() {
        if (isset($this->firstname) && isset($this->lastname)) {
            return $this->firstname . " " . $this->lastname;
        } else {
            return "";
        }
    }

    private static function instantiate($record) {
        $object = new self;

        foreach($record as $attr=>$value){
            if($object->hasAttr($attr)) {
                $object->$attr = $value;
            }
        }
        return $object;
    }

    private function hasAttr($attr) {
        $objectVars = get_object_vars($this);
        return array_key_exists($attr, $objectVars);
    }
}

?>

1 个答案:

答案 0 :(得分:0)

嗯,您的代码有效。这是一个自包含的例子:

<?php
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "sotest_users");

function query($mysqli, $text) {
    print 'Query: ' . $text . PHP_EOL;
    $result = $mysqli->query($text);
    if ($result === false) {
        print 'Query error: ' . $mysqli->error . PHP_EOL;
        die();
    }
    return $result;
}

$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS);
query($mysqli, 'drop database if exists ' . DB_NAME);
query($mysqli, 'create database ' . DB_NAME);
$mysqli->select_db(DB_NAME);
query($mysqli, 'create table users (userId integer, username text, password text)');
query($mysqli, 'insert into users (userId, username, password) values (1, "test", "test")');

$result = query($mysqli, 'select * from users where userId=1');
while ($row = $result->fetch_assoc()) {
    print json_encode($row) . PHP_EOL;
}
$result->close();


// Your code here

class Database {
    //...
}

$db = new Database();

class User {
    //...
}

print 'Start' . PHP_EOL;
$user = User::getUserId(1);
var_dump($user);
//echo $user->getName();

输出:

Query: drop database if exists sotest_users
Query: create database sotest_users
Query: create table users (userId integer, username text, password text)
Query: insert into users (userId, username, password) values (1, "test", "test")
Query: select * from users where userId=1
{"userId":"1","username":"test","password":"test"}
Start
class User#6 (8) {
  public $userId =>
  string(1) "1"
  public $username =>
  string(4) "test"
  public $password =>
  string(4) "test"
  public $email =>
  NULL
  public $firstname =>
  NULL
  public $lastname =>
  NULL
  public $access =>
  NULL
  public $active =>
  NULL
}

完整代码为herepassword之后的字段仅为空,因为我没有将它们添加到users表中。

但是我必须说,你在OOP(全局变量,静态方法,公共属性等)和db处理(缺少错误处理,直接变量注入)方面做的一般都是错误的进入sql)。

如果这是一个真实的项目 - 更好地切换到某个框架,例如Yii

如果您正在学习 - 在php中查找并阅读有关正确的OOP使用和最佳数据库实践的内容。 PHP The Right Way是一个很好的起点。