I am new to OOP, so I am trying to learn how to create classes and use them. Currently I am trying to fetch data from my MySQL table.
To create the connection with M
IMHO you can just inject the PDO connection into the functions that need it:
<?php
$dbHandle = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$dbHandle->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// always disable emulated prepared statement when using the MySQL driver
$dbHandle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
function get_all($dbHandle) {
$sql = "SELECT * FROM information";
$stmt = $dbHandle->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
return $stmt;
}
get_all($dbHandle);
If you really think you need some class to access to database (other than PDO) (which you don't need) you would have to extend PDO:
<?php
class DBConnection extends PDO
{
public function __construct()
{
parent::__construct("mysql:host=$host;dbname=$dbname", $user, $pass);
$this->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// always disable emulated prepared statement when using the MySQL driver
$this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
}
$dbHandle = new DBConnection();
function get_all($dbHandle) {
$sql = "SELECT * FROM information";
$stmt = $dbHandle->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
return $stmt;
}
get_all($dbHandle);
Maybe change the DBConnections FUNCTION to a __contstruct() function. In addition, you'd need to extend the PDO class to use all the methods within it.