显示表中的所有用户并删除所选的用户

时间:2014-01-12 18:15:43

标签: php

如何在html表中显示数据库中users表中的所有用户? 我必须在html表中显示所有用户,并且可以使用复选框选择每个用户。然后从数据库中删除所选用户。 我正在使用mvc技术,我有一个页面“DeleteUser”,只包含html,控制器和公共文件。

查看/ DeleteUser.php 包含:

 <form method="post" action="../public/deleteUser.php">
    <table>  
        <tr>
           <td>#</td>
           <td>Username</td>
           <td>First name</td>
           <td>Last name</td>         
           <td>City</td>
           <td>Gender</td>
           <td>E-mail</td> 
           <td>Check</td> 
        </tr>

        <tr>
           <td><input type="submit" name="submit-deleteuser" value="Delete user"/></td>
        </tr>
    </table>
  </form>

public / deleteUser.php 包含:

  $controller = new DeleteUserController();
  $view = $controller->invoke();
  $view->render();

Controller / DeleteUserController.php 中的 invoke()方法包含:

  class DeleteUserController {

     public $user;
     public $users;
     public $userRepository;
     public $view;

     public function __construct() {
        $username = $_SESSION['username']; 
        $this->userRepository = new UserRepository();
        $this->user = $this->userRepository->findByUsername($username);    
        $this->users = array();
        $this->view = new View('DeleteUser');
        $db = Database::getInstance();
     }

     public function listUsers() {
        $this->users = $this->userRepository->fetchAll();
        foreach($this->users as $u) {
           $str = "<tr>
                       <td><?php $u->getId() ?></td>
                   </tr>";    
        }
     }

     public function deleteUsers() {
        if(isset($_POST['submit-deleteuser'])) {
           $del_id = $_POST['users'];
           foreach($del_id as $value) {
              $value->delete();
           }
        }      
     }

     public function work() {
        $this->listUsers();
        $this->deleteUsers();
     }

     public function invoke() {
        $this->work();
        $this->view->setData('user', $this->user);
        return $this->view;   
     }

如果我不必使用mvc,我会这样做:

  <table>  
     <tr>
        <td>#</td>
        <td>Username</td>
        <td>Fisrt name</td>
        <td>Last name</td>         
        <td>City</td>
        <td>Gender</td>
        <td>E-mail</td> 
        <td>Check</td> 
     </tr>
     <?php
        $utente = $_SESSION['username'];
        $query = "SELECT * FROM users ORDER BY id";
        $result = mysql_query($query);
        while($row = mysql_fetch_array($result)) {
              echo "<tr>
                       <td>$row[id]</td>
                       <td>$row[username]</td>
                       <td>$row[fisrt_name]</td>
                       <td>$row[last_name]</td>
                       <td>$row[city]</td>
                       <td>$row[gender]</td>
                       <td>$row[email]</td>    
                       <td><input type=\"checkbox\" name=\"users[]\" value=\"" .$row['id']. "\"></td>   
                    </tr>";                                    
           }
        }
     ?>
     <tr>
        <td colspan="9"><input type="submit" name="submit-deleteuser" value="Delete users"/></td>
     </tr>
  </table>

但现在我不知道该怎么办。两个方法 listUsers() deleteUsers()是错误的,不知道如何完成它们或纠正它们。 首先它很简单,我把PHP代码显示在我想要的html标签中(<table>...</table>),但现在呢? 我不知道如何处理这件事。 给我建议?谢谢:))


fetchAll()是:

    public function fetchAll(){
    $db = Database::getInstance();
    $stmt = $db->prepare("SELECT * FROM `users`");
    $stmt->execute();
    $users = array();
    while($result = $stmt->fetch()) {
        $users[] = User::load($result);
    }   
    return $users;
}

1 个答案:

答案 0 :(得分:1)

尝试使用MVC模式是令人钦佩的,但在这种情况下有一点点:)。缺少的是控制器动作的概念。

也许尝试重构一下这样的代码:

目录结构

  • 控制器/
    • UsersController.php
  • 模型/
    • UsersModel.php
    • View.php
  • 视图/
    • header.tpl.php
    • footer.tpl.php
    • 用户/
      • list.tpl.php
      • delete.tpl.php
  • users.php

<强> 1。从与数据库交互的用户模型开始

class UsersModel {

    public function fetchAll() {
        $result = array();

        // Build SELECT query, fetch all users from db., and store in $result
        // ...

        return $result;
    }

    public function deleteMany(array $ids) {
        $result = array();

        // Build DELETE query, execute it, and store the number of affected records in $result
        // ...

        return $result;
    }
}

<强> 2。创建UsersController而不是DeleteUserController。创建两个方法:listUsersAction和deleteUsersAction。

class UsersController {

    public function listUsersAction() {
        $model = new UsersModel();
        $data = $model->fetchAll();

        return new View(
            'users/list',
            $data
        );
    }

    public function deleteUsersAction() {
        // This is simplistic, but the idea is to get the required input from the request (and actually validate it!)
        // Also see the users/list template further down
        $ids = $_POST['user_ids'];

        $model = new UsersModel();
        $numRecords = $model->deleteMany($ids);

        return new View(
            'users/delete',
            array('deleted_records' => $numRecords)
        );
    }
}

第3。我们的View类应存储模板名称和视图数据,并能够呈现模板

class View {

    public static $viewDirectory;

    public $template;
    public $data = array();

    public function __construct($template, $data) {
        if (!View::$viewDirectory) {
            View::$viewDirectory = dirname(__FILE__) . '/views/';
        }

        $this->template = $template;
        $this->data = $data;
    }

    public function render() {

        // Make the data available in the template
        $data = $this->data;

        // Include the template.
        require(realpath(View::$viewDirectory . $this->template . '.tpl.php'));
    }
}

<强> 4。用户/列表模板可能看起来像这样

// views/users/list.tpl.php
<form action="/users.php?action=delete" method="post">
<?php foreach ($data as $user): ?>
<div>
    <input type="checkbox" name="user_ids[<?= $user['id'] ?>]" value="1"/>
    <?= $user['username'] ?>
</div>
<?php endforeach; ?>
</form>

<强> 5。在users.php中将所有内容联系在一起

<?php
    // users.php

    // (include all previously defined classes here)

    // We'll want to include a HTML header of some sort:
    include("views/header.tpl.php");

    /**********
     *  Poor man's routing; valid urls:
     *  /users.php?action=listUsers
     *  /users.php?action=deleteUsers with POST data
     */

    // Determine the action from the GET parameter. If no action is set, the default action is listUsers

    //$action = (array_key_exists('action', $_GET) ? $_GET['action'] : 'listUsers');

    // Equivalent of:
    if (array_key_exists('action', $_GET)) {
        $action = $_GET['action'];
    } else {
        $action = 'listUsers';
    }
    //--

    $actionMethod = $action . 'Action';

    $controller = new UsersController();

    if (method_exists($controller, $actionMethod)) {
        $view = $controller->$actionMethod();
        $view->render();

    } else {
        echo "<div class='error'>The action '$action' is invalid for the Users controller.'</div>";
    }

    // We'll want to include a footer as well:
    include("views/footer.tpl.php");
?>