Reputation: 4491
This may be a question that has been answered before - if so please just leave a comment below and I'll remove this one.
I have been learning classes in PHP and at the same time making the jump to PDO.
One concept I cant seem to find is how to acomplish the equivalent to this with classes:
config.php
<?php
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$con = mysql_connect($host, $user, $pass) or die("MySQL Error");
mysql_select_db("account_db", $con);
?>
another.php
<?php
require_once('config.php');
$selectStatement = "SELET foo FROM bar";
$selectQuery = mysql_query($selectStatement, $con);
?>
I haven't quite figured out how I would create a config file/class for a PDO connection and then use it in another class, i.e. Users as below:
<?php
class Users
{
private $_userId;
function setUserId($username)
{
// Use a predefined database handle to connect to a database to get the users ID - I assume using a preconfigured $dbh handle via an include or extend?
$sth = $dbh->prepare("SELECT id FROM users WHERE username = :username");
$sth->bindParam(':username', $username);
...
}
}
?>
Thanks all :)
Upvotes: 6
Views: 8544
Reputation:
In my projects, I prefer using a class with a static member which holds the PDO object.
<?php
class DB
{
private static $instance = null;
public static function get()
{
if(self::$instance == null)
{
try
{
self::$instance = new PDO('mysql:host=localhost;dbname=name', 'user', 'abc123');
}
catch(PDOException $e)
{
// Handle this properly
throw $e;
}
}
return self::$instance;
}
}
The I can access it like so:
<?php
require 'DB.php';
class Users
{
private $_userId;
function setUserId($username)
{
// Using DB::get() to get the PDO object
$sth = DB::get()->prepare("SELECT id FROM users WHERE username = :username");
$sth->bindParam(':username', $username);
...
}
}
Upvotes: 10