我在将数据库对象传递给类时遇到问题。运行 index.php 时收到以下错误:
“警告:缺少 Client::__construct() 的参数 1,在第 14 行 C:\xampp\htdocs\mobile_dispatch\index.php 中调用并在 C:\xampp\htdocs 中定义第 25 行的\mobile_dispatch\classes\class.client.inc
注意: undefined variable :第 26 行 C:\xampp\htdocs\mobile_dispatch\classes\class.client.inc 中的 db
fatal error :在第 32 行对 C:\xampp\htdocs\mobile_dispatch\classes\class.client.inc 中的非对象调用成员函数prepare()”
我不确定如何将 $db 对象从 mysql_login_pdo.php 传递到 Client 类。感谢您的帮助。
这是有问题的代码:
index.php
<?php
require_once './classes/class.client.inc';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mobile Dispatch</title>
</head>
<body>
<?php
echo 'Hello World! The database connected just fine ;)';
$client = new Client;
$client->add_to_db();
?>
</body>
</html>
class.client.inc
<?php
require './classes/mysql_login_pdo.php';
class Client {
public $firstName;
public $middleName;
public $lastName;
public $streetAddress1;
public $streetAddress2;
public $city;
public $state;
public $zip;
public $phone_home;
public $phone_cell;
public $phone_office;
protected $db;
public function __construct($db) {
$this->db = $db;
}
public function add_to_db() {
$query = "INSERT INTO `clients` "
. "VALUES (:id, :firstName, :middleName, :lastName)";
$stmt = $this->db->prepare($query);
$stmt->execute(array(
':id' => null,
':firstName' => 'Mary',
':middleName' => 'G',
':lastName' => 'Smith'
));
}
}
mysql_login_pdo.php
<?php
$host = "localhost"; //Host Name
$port = '3306'; //Default MySQL Port
$dbname = "mobile_dispatch"; //Database Name
$db_username = "user"; //MySQL Username
$db_password = "password"; //MySQL Password
//Data Source Name = Mysql
$dsn = "mysql:host=$host;port=$port;dbname=$dbname";
//Try to connect to the database and return the $db connection info. if not,
//stop processing all scripts and return a generalised message
try {
$db = new PDO($dsn, $db_username, $db_password); //Connect to DB
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERR_NONE);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //Creates TRUE prepared statements
} catch (Exception $e) {
die("Cannot connect to database");
}
编辑: 更新了index.php:
<?php
require_once './classes/mysql_login_pdo.php';
require_once './classes/class.client.inc';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mobile Dispatch</title>
</head>
<body>
<?php
echo 'Hello World! The database connected just fine ;)';
$client = new Client($db);
$client->add_to_db();
?>
</body>
</html>
这会导致以下错误: fatal error :在第 31 行对 C:\xampp\htdocs\mobile_dispatch\classes\class.client.inc 中的非对象调用成员函数execute()
最佳答案
您必须在构造函数中传递 $db 参数:
$client = new Client($db);
关于php - 将 PDO 数据库对象从包含脚本传递到类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25144553/