所以我正在尝试构建一个简单的 PDO 连接类,这样我就可以在需要访问数据库时创建一个数据库对象,但无论我尝试什么,我都会遇到同样的错误。
这是我的 DB 类代码
<?php
class DbConnect
{
// Database login vars
private $dbHostname = 'localhost';
private $dbDatabase = 'database';
private $dbUsername = 'username';
private $dbPassword = 'password';
public $db = null;
public function connect()
{
try
{
$db = new PDO("mysql:host=".$this->dbHostname.";dbname=".$this->dbDatabase, $this->dbUsername, $this->dbPassword); // Establish DB connection
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set error handling
return $db;
}
catch(PDOException $e)
{
echo "It seems there was an error. Please refresh your browser and try again. ".$e->getMessage();
}
}
}
?>
这是我试图在其中使用它的类的代码:
<?php
session_start();
require 'DbConnect.php';
class User
{
public function bindParams()
{
$DbConnect = new DbConnect();
$sql = $DbConnect->connect();
$sql->prepare("insert into dbobjectex(firstName, lastName) values (:firstName, :lastName)");
$sql->bindParam(':firstName', $_SESSION['firstName']);
$sql->bindParam(':lastName', $_SESSION['lastName']);
$sql->execute();
}
}
?>
然后从我创建 User 类的位置调用 bindParams()。我不断收到的两个错误是“NetworkError: 500 Internal Server Error”和“The character encoding of the HTML document was not declared”。关于我在这里做错了什么的任何想法?感谢您的任何建议。