如何将多个用户从数据库分配到类属性?

时间:2012-10-19 09:26:06

标签: php class orm

我无法弄清楚如何将每个用户从我的数据库中分配为类属性并显示它们。看一看。例如,我在我的数据库中有这个表:

+----+----------+------------+-----------+
| id | username | first_name | last_name |
+----+----------+------------+-----------+
|  1 | guu      |  Guu       | GuuShtein |
|  3 | user1    |  Allan     | Last      |
|  4 | Donny    |  Name      | Last Name |
+----+----------+------------+-----------+

这是班级:

class users {

public $db;
private $id;
private $username;
private $first_name;
private $last_name;

public function __construct($db) {
    $this->db=$db;
}

private function find_by_id($id) {
   $record = $this->db->query('SELECT * FROM users WHERE id=' . $id .' LIMIT 1')->fetch(PDO::FETCH_ASSOC);     
   foreach ($record as $atribute => $value) {
       $this->$atribute = $value;
   } 
}

public function user_nfo($id){
    $this->find_by_id($id);

    $user_nfo = "User id: " . $this->id . "<br />";
    $user_nfo .= "Username: " . $this->username . "<br />";
    $user_nfo .= "User full name: " . $this->first_name . " " . $this->last_name . "<br />";       
    return $user_nfo;
}
}

$users = new mysql_a($db);
echo $users->user_nfo(1);

我的问题是如何编写一个方法,逐个显示所有用户?我的意思是类似于我的user_nfo函数,但仅适用于所有记录?我尝试使用PDOfetchAll进行“foreach”循环,但它只是覆盖属性并且只显示最后一条记录。

2 个答案:

答案 0 :(得分:2)

你想要的是一个名为user的新对象,它拥有你想要的所有属性,如下所示。

<?php

try {
    $db = new PDO('mysql:host=localhost;dbname=sub_db;charset=UTF-8', DB_USER, DB_PASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
} catch (PDOException $ex) {
    echo "error";
}

class users {

    public $db;

    public function __construct($db) {
        $this->db=$db;
    }

    /**
     * Fetch all users and return an array of their mapped objects
     *
     * @author Daniel Noel-Davies
     *
     * @return array
     */
    public function getAllUsers () {
        $users   = array();

        // Grab an array of each user
        $users = $this->db->query('SELECT * FROM users')->fetch(PDO::FETCH_ASSOC);

        // Loop through the users
        foreach( $users as $index => $user ) {
            // Replace each row with an object of that user (keeps memory down)
            $users[$index] = new User($user);
        }

        // return our array containing an object of each user
        return $users;
    }

    public function count_row(){
        $count = $this->db->query('SELECT COUNT(*) FROM users')->fetch(PDO::FETCH_ASSOC);
        return $count['COUNT(*)'];
    }

    public function find_by_id($row) { 
       $record = $this->db->query('SELECT * FROM users LIMIT 1 OFFSET ' . $row)->fetch(PDO::FETCH_ASSOC);
       return $record;
    }   
 }


class user {

    public $id;
    public $username;
    public $first_name;
    public $last_name;

    public function __construct($record){    
           foreach ($record as $atribute => $value) {
               $this->$atribute = $value;
           }
    }
}

// Initiate our users class
$objUsers = new Users;

// Fetch all the users
$users = $objUsers->getAllUsers();

// Loop through them all
foreach ($users as $user) {
    // Using Printf keeps things neater, means you're template is tidier.
    printf(
        '%s<br />
        %s<br />
        %s<br />
        %s<br />',

        $user->id,
        $user->username,
        $user->first_name,
        $user->last_name
    );
}
?>

这有帮助吗?

答案 1 :(得分:0)

感谢“NoelDavies”的回答,这是我设法为我工作的完整代码。如果有人遇到同样的问题:

<?php

try {
$db = new PDO('mysql:host=localhost;dbname=sub_db;charset=UTF-8', DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
} catch (PDOException $ex) {
    echo "error";
}

class mysql_a {

    public $db;

    public function __construct($db) {
        $this->db=$db;
    }

    public function count_row(){
        $count = $this->db->query('SELECT COUNT(*) FROM users')->fetch(PDO::FETCH_ASSOC);
        return $count['COUNT(*)'];
    }

    public function find_by_id($row) { 
       $record = $this->db->query('SELECT * FROM users LIMIT 1 OFFSET ' . $row)->fetch(PDO::FETCH_ASSOC);
       return $record;
    }   
 }


class user {

    public $id;
    public $username;
    public $first_name;
    public $last_name;

    public function __construct($record){    
           foreach ($record as $atribute => $value) {
               $this->$atribute = $value;
           }
    }
}


$users = new mysql_a($db);

for ($i = 0; $i < $users->count_row(); $i++) {
    $user = new user($users->find_by_id($i));
    echo $user->id         . "<br />";
    echo $user->username   . "<br />";
    echo $user->first_name . "<br />";
    echo $user->last_name  . "<hr />";
}
?>

它计算db中的行数,然后逐个将它们拉出并输出。我确信有一些更短更优雅的方式,但现在对我来说效果很好;]再次感谢“NoelDavies”。