Reputation: 87
i've been coding php for quite a while now but i recently got into object oriented programming.
Before i used mysql_connect(),mysql_query() and all those functions but then i heard that PDO would be way better alternative.
I thought why not and watched a basic PDO video.
try {
global $db;
$db = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pw);
} catch (PDOException $e) {
die("ERROR: " . $e->getMessage());
}
print(gettype($db)."<br>");
function test() {
print(gettype($db));
}
test();
So the problem here is, i want to create a function so i can easily insert new items into my table. But i ran to this problem, my $db is not global. So i would have to re-connect to my database when using the function, but i can't do that, it would not be good at all.
So how can work around this problem? Oh and the above code outputs:
object
Notice: Undefined variable: db in /home/vhosts/ollie.ceify.net/www/ip-bless/connect.php on line 25 NULL
Upvotes: 4
Views: 5039
Reputation: 347
Create a on object that holds a private PDO Object and define a public query method that accepts table name, column name, and value arguments and can be called repeatedly:
class DatabaseObject{
private $db;
public function __construct() {
$this->createDB();
}
private function createDB() {
$this->db = PDO("mysql:host=localhost;dbname=yourdatabase", 'username', 'password');
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function insert($table, $column, $value) {
try {
$this->db->query(sprintf("
INSERT INTO %s (%s)
VALUES (%s)",
$table, $column, $value));
}
catch (PDOException $e) {
return $e->getMessage();
}
}
}
$db = new DatabaseObject();
$db->insert('table_name', 'column_name', 'value');
Upvotes: 3
Reputation:
What I normally do is defining a function for connecting to the database or getting the already available handle.
function dbHandle()
{
global $dbh;
if (is_resource($dbh)) return $dbh;
return $dbh = new PDO(...); # All your DB credentials here.
}
...as a simple example, if you have a more complicated setup you can, for example, store this information in static members of a class.
Upvotes: 0
Reputation: 7040
Pass the variable to your function as a parameter.
function test($dbObj) {
print(gettype($dbObj));
}
OR
You can place your functions inside an object and have $db
as a member variable:
class myClass {
public $db;
public function __construct($dbObj) {
$this->db = $db;
}
public function test() {
print(gettype($this->db));
}
}
$myVar = new myClass();
$myVar->test();
Upvotes: 1
Reputation: 160833
You need use global
to get the global variable too.
function test() {
global $db;
print(gettype($db));
}
Upvotes: 1