I’ve been playing around with PDO and created this class.
Do you think this is efficient code? Look at the way I’ve created two different methods and called the first in the second
class Database
{
public function connect_database()
{
# connect to the database
try {
$dsn = 'mysql:dbname=testing;host=localhost';
$user = 'root';
$password = '';
$DBH = new PDO($dsn, $user, $password);
// There are three different levels of PDO error message: http://php.net/manual/en/pdo.error-handling.php
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
return $DBH;
}
catch (PDOException $e) {
echo "There has been an error connecting to the database: ";
echo br;
echo $e->getMessage();
}
} // End function connect_database();
public function select_data($sql)
{
// Call connect_database() method
$DBH = $this->connect_database();
try {
$query = $DBH->query($sql);
while ($result = $query->fetch(PDO::FETCH_ASSOC)) {
return $result;
}
}
catch (PDOException $e) {
echo "There has been an error with this select query: ";
echo br;
echo $e->getMessage();
}
} // End public function select data
} // End class Database
$db = new Database();
$db->select_data("SELECT * FROM user");