2016-08-03 90 views
0

我正在尝试使用php oop显示我的数据库中的所有用户。我真的不知道如何包含user.php的成connectionFile.php或一些可能work.my代码:user.php的:显示数据库中的所有用户php oop

public class User{ 
    protected $firstname; 
    protected $lastname; 
    protected $email; 
    protected $password; 
    protected $age; 
    protected $role; 
    protected $file; 
    protected $db; 

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

    public function __construct($firstname, $lastname, $email){ 
     $this->firstname = $firstname; 
     $this->lastname = $lastname; 
     $this->email = $email; 
    } 

    public function getFirstname(){ 
     return $this->firstname; 
    } 
    public function getLastname(){ 
     return $this->lastname; 
    } 
    public function getEmail(){ 
     return $this->email; 
    } 

    public function setFirstname($firstname){ 
     $this->firstname = $firstname; 
    } 
    public function setLastname($lastname){ 
     $this->lastname = $lastname; 
    } 
    public function setEmail($email){ 
     $this->email = $email; 
    } 
    public function getAllUsers(){ 
     try{ 
      $stmt = $this->db->prepare("select * from user"); 
      $stmt->execute(); 
      return $stmt; 

     }catch(PDOException $e){ 
      echo $e->getMessage(); 
     } 
    } 
    } 

我connectionFile.php:

require_once ("user.php"); 
// session_start(); 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
$database = "first_project"; 
try { 
    $conn = new PDO("mysql:host=$servername;dbname=first_project", $username, $password); 
    // set the PDO error mode to exception 
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    // echo "Connected successfully"; 
} 
catch(PDOException $e){ 
    echo "Connection failed: " . $e->getMessage(); 
} 

和我displayResult.php(我也有形式的页面HTML):

<?php 
require_once("connectionFile.php"); 
//include_once 'user.php'; 
if(isset($_POST['button'])){ 
    //$user = new User(); 
    echo "skksksks"; 
} 
else{ 
    echo "v"; 
} 

?> 

的按钮工作,我想在按钮后调用从用户类功能getAllusers但我真的不知道该怎么因为每一次我尝试将该文件包含在任何地方,以使我找不到页面。

+0

你已经包括connectionFile user.php的文件。 PHP。您不需要将其包含在displayResult.php中 –

回答

0

您可以创建类的对象来访问方法。

require 'user.php'; 
$obj=new User($db_con); 
$obj->setFirstName('test'); 

等等...

并请确保您可以重载在PHP构造...我不这么认为..