我有一个成功连接到我的本地主机和我的数据库的数据库类,我想选择我的用户数据库中的所有用户,但是当我调用我的数据库时,事实证明这比我想象的要困难得多。
我收到很多错误,例如:
Notice: Undefined variable: host in E:\xampp\htdocs\attendance\class.Register.php on line 10
Notice: Undefined variable: dbname in E:\xampp\htdocs\attendance\class.Register.php on line 10
Notice: Undefined variable: user in E:\xampp\htdocs\attendance\class.Register.php on line 10
Notice: Undefined variable: pass in E:\xampp\htdocs\attendance\class.Register.php on line 10
Fatal error: Call to undefined method Database::prepare() in E:\xampp\htdocs\attendance\class.Register.php on line 17
但是我已经在我的数据库类中定义了这些,并告诉我的注册类需要连接文件。我究竟做错了什么?我似乎无法弄清楚我应该如何在我的注册类中调用我的数据库连接?有人有想法么?
类.Connect.php
<?php
// Database connection PDO
class Database {
public function __construct() {
// Connection information
$host = 'localhost';
$dbname = 'imanage';
$user = 'root';
$pass = '';
// Attempt DB connection
try
{
$this->pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Successfully connected to the database!';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function __destruct()
{
// Disconnect from DB
$this->pdo = null;
//echo 'Successfully disconnected from the database!';
}
}
?>
类.Register.php
<?php
require 'class.Connect.php';
class Register {
public function __construct()
{
$this->pdo = new Database($host, $dbname, $user, $pass); //ofcourse you can get the db connections details and database name from a config file
}
public function viewall() {
$sql = "SELECT * FROM users";
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
// here you go:
$users = $stmt->fetchAll();
foreach ($users as $row) {
print $row["firstname"] . "-" . $row["lastname"] ."<br/>";
}
}
}
$run = new Register();
$run->viewall();
?>