我试图使用php oop显示我的数据库中的所有用户。我真的不知道如何将user.php包含到connectionFile.php或可能起作用的地方。我的代码:user.php:
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但我真的不知道如何,因为每次我尝试将该文件包含在任何位置时都会找不到页面。< / p>
答案 0 :(得分:0)
您可以创建类的对象来访问方法。
require 'user.php';
$obj=new User($db_con);
$obj->setFirstName('test');
依旧......
请确保你能在php中重载构造函数......我不这么认为..