Reputation: 1801
So I'm trying to build a simple PDO connection class so I can create a DB object whenever I need to have DB access but I keep getting the same errors no matter what I try.
Here is my code for the DB class
<?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();
}
}
}
?>
And here is my code for the class I'm trying to use it in:
<?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();
}
}
?>
Then bindParams() is called from the spot where I create the User class. The two errors I keep getting are "NetworkError: 500 Internal Server Error" and "The character encoding of the HTML document was not declared." Any ideas on what I'm doing wrong here? Thanks for any advice.
Upvotes: 0
Views: 1407
Reputation: 76395
What am I doing wrong here?
- Many things, but the most obvious one to miss is this: at the end of your class definition of DbConnect
, you're closing the php tag ?>
, which you must avoid as much as possible with included files with included files. The upshot of having them in your case is that headers are sent prematurely, explaining your second error.
Other then that, each time you're instantiating the user class, you're creating a new PDO instance: you assign it to a variable, local to the connect
member function, at least replace $db
with $this->db
. But most of all, I agree with @sabre: why would PDO require an additional wrapper? especially one that does nothing more than instantiate and return a pdo instance, just create an abstract class that handles the connections if needs must.
Another thing you might want to check is weather or not the include path is correct, and read the docs on autoloading classes. It'll save you a world of trouble once you've got a substantial class library. This might explain your first error, as might the ?>
tag, but just to be on the safe side: use require_once
, rather than require
: including, and thus redefining, a class a second time is not what you want to be doing at all.
Upvotes: 1