I am trying to use PDO statements in my classes. I am new to oop and I am trying to figure out how it is supposed to be done. I looked at some of the examples on this site, and used their logic but none of them seemed to work. There were no fatal errors, or warnings in the source code but the sql statement was never executed. So I feel I'm just missing one small thing that I haven't learned yet.
So far what I have learned is that the PDO connection has to be made in a class and should be called via the constructor method. I got the code for the database class from someone else.
class Database
{
protected static $Connection;
public static function Connect()
{
if((self::$Connection instanceof PDO) === false)
{
$dbhost = 'host';
$dbname = 'name';
$dbuser = 'user';
$dbpass = 'pass';
self::$Connection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
return self::$Connection;
}
}
And this is just the constructor and an example a PDO statement in one of the functions of the class
class blahJR extends blah
{
private $Database;
function __construct ($sUser)
{
parent::__construct($sUser);
//Updated below: $this->Database = Database::Connect();
$this->Database = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); //All the variables are given and the connection is definitely being made
} //end __construct
public function foo($sString)
{
try
{
$Statement = $this->Database->prepare("INSERT INTO table (column) VALUES (?)");
$Statement->execute(array($sString));
}
catch (PDOexception $e)
{
DatabaseError($e);
}
}
Any help would be greatly appreciated. Thank you for your time.
Updated: I added the function around the try statement to make it more clear, it was always there, I just never added it when I made the question. I hope that clarifies it. It doesn't report any errors still. I have no idea why this shouldn't work.