gpt4 book ai didi

php - 如何从不同的类调用我的数据库类

转载 作者:太空宇宙 更新时间:2023-11-03 12:23:06 25 4
gpt4 key购买 nike

我有一个成功连接到我的本地主机和我的数据库的数据库类,我想选择我的用户数据库中的所有用户,但是当我调用我的数据库时,事实证明这比我想象的要困难.

例如,我遇到了很多错误:

注意: undefined variable :host in E:\xampp\htdocs\attendance\class.Register.php on line 10

注意:第 10 行 E:\xampp\htdocs\attendance\class.Register.php 中 undefined variable :dbname

注意: undefined variable :用户在 E:\xampp\htdocs\attendance\class.Register.php 第 10 行

注意: undefined variable :在第10行传入E:\xampp\htdocs\attendance\class.Register.php

fatal error :在第 17 行调用 E:\xampp\htdocs\attendance\class.Register.php 中未定义的方法 Database::prepare()

但是我已经在我的数据库类中定义了这些,并告诉我的注册类需要连接文件。我究竟做错了什么?我似乎无法弄清楚我应该如何在我的注册类中调用我的数据库连接?有人有什么想法吗?

类.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();
?>

最佳答案

您正在使用 $this->pdo 来定义您的数据库连接,但忘记为类定义属性。

定义类属性如下。

class Register
{
private $pdo;
public function __construct()
{
$this->pdo = new Database();
}

您的 Database 类构造函数不接受任何参数,因此在创建 Database 类的对象时避免传递参数。

关于php - 如何从不同的类调用我的数据库类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18868368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com