How to connect to database using PDO in multiple classes? - php

I have multiple classes and most of them need to connect to database,
How can I set PDO options/host/dbname etc only once and then use it in every class while having the following in mind:
I don't want to wrap PDO
I need to close the PDO connection after each query ($db=null), so I simply cannot just use $db = new PDO(...) and then pass $db to my classes
I want to skip having this in every class that needs to connect to the database:
<?php
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

If you want complete control over opening and closing connections then I suggest we only centralise the $dsn, $user, $pass and $options variables. I'm assuming there are also variables like $host, $db and $charset which you did not reveal to us but lets add them.
Lets call this file global_db.php:
<?php
$host = "127.0.0.1";
$db = "mydb";
$charset = "UTF-8";
$user = "root";
$pass = "";
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
That looks like we have all the goods there, keep in mind I am not testing this so we might get a syntax error or two.
Now in our classes or other php files where we want to open a connection.
Lets call this page fooClass.php
<?php
require_once 'global_db.php';
class FooClass {
public function __construct() {
try {
$pdo = new PDO(
$GLOBALS['dsn'],
$GLOBALS['user'],
$GLOBALS['pass'],
$GLOBALS['options']);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
}
}
That should do the trick or at least give you a general idea on where to go from here on your own route. There are many other ways to accomplish similar but no need to overcomplicate things.
nJoy!

Related

Uncaught TypeError: PDO::__construct() expects parameter 1 to be string

I have searched the forum, but I have not found anything directly related to my issue. I am fairly new to PDOs and class OOP creation. I am trying to create a database connection class where I can instantiate the connection as needed. I having issues instantiating my connection.
File Organization:
parent directory (folder)
|
private (folder)
|
config.php
classes (folder)
|
class1.class.php
DatabaseConnection.class.php
db_cred.inc.php
public (folder)
|
search.php
Process:
I have created a database credential php file "db_cred.inc.php"
I have a database connection class called "DatabaseConnect" in "DatabaseConnect.class.php" file
I load those files as follows
require_once 'db_cred.inc.php'; in the "DatabaseConnect.class.php" file
spl_autoload_register for all of my class files
Expected actions:
When my "search.php" page request data from mysql via a pdo, a new database connection will instantiate a new connection via the "openConnection()" method.
The class "DatabaseConnection" will load the credentials from "db_cred.inc.php" as a sting and connect to the database
The class will then use the credentials to connect to the mysql database, and execute the requested pdo query returning the results and storing them into a variable "$row".
Issue:
When I execute the pdo, the following error is returned:
Uncaught TypeError: PDO::__construct() expects parameter 1 to be string, array given in private/classes/DatabaseConnect.class.php:21 Stack trace: #0 private\classes\DatabaseConnect.class.php(21): PDO->__construct(Array) #1 \public\search.php(53): DatabaseConnect->openConnection() #2 {main} thrown in \private\classes\DatabaseConnect.class.php on line 21
spl_autoload_register() in the config.php file
function my_autoload($class) {
if(preg_match('/\A\w+\Z/', $class)) {
require ('classes/' . $class . '.class.php');
}
}
spl_autoload_register('my_autoload');
Credential setup in "db_cred.inc.php"
<?php
// define an array for db connection.
define("DB", [
"DB_HOST" => "mysql:host=localhost",
"DB_USER" => "user",
"DB_PASS" => "pass",
"DB_DATABASE" => "mytestdb",
"DB_CHAR" => "utf8",
]);
?>
My class for database connection:
<?php
require_once 'db_cred.inc.php';
// creating db connection class
class DatabaseConnect {
private $server = 'DB_HOST';
private $database = 'DB_DATABASE';
private $pass = 'DB_PASS';
private $user = 'DB_USER';
private $opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
protected $con;
public function openConnection() {
**ERROR TAKES PLACE HERE**
try {
$this->con = new PDO([$this->server, $this->database, $this->user, $this->pass]);
return $this->con;
} catch(PDOExeption $e){
echo "ERROR: " . $e->getMessage(), (int)$e->getCode();
}
}
public function closeConnection() {
$this->con = null;
}
}
?>
PDO for search.php
<?php
$dbconn = new DatabaseConnect();
$pdo = $dbconn->openConnection();
$sql = "SELECT * FROM report";
foreach ($pdo->query($sql) as $row) {
echo " PI: ".$row['pi'] . "<br>";
}
?>
I am not sure what is causing the error. I am sure it is due to my inexperience with classes and oop. It appears that the config.php file is working fine. The class is identified by the request because the error happens inside the PDO __construct method. Please help.
UPDATE - MY WORKING SOLUTION
I hope this might help someone moving forward with a similar question. I am not finished with the development of this process, but this kicked in a huge door.
My revised class
<?php
// Associating db_cred.inc.php with class
require_once('db_cred.inc.php');
// Creating db connection class
class DatabaseConnect {
/*
!! Assigning defined constants per define('DB_CONSTANT', 'value') loaded from "db_cred.inc.php" file to variables
!! "db_cred.inc.php" should not be loaded into the "config.php" file
!! BECAUSE THE VALUES OF THE VARIABLES ($variable) ARE CONSTANTS (DB_CONSTANT), DO NOT USE SINGLE OR DOUBLE QUOTES. THE PDO __CONSTRUCT FUNCTION WILL IGNORE THE VALUE OF THE VARIABLE
*/
private $host = DB_HOST;
private $database = DB_DATABASE;
private $pass = DB_PASS;
private $user = DB_USER;
private $char = DB_CHAR;
// Setting attributes and storing in variable $opt
private $opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// $con variable will store PDO connection and is set to NULL
private $con;
// Create Connection to database
public function openConnection() {
// Setting $con to null
$this->con = NULL;
// If $con is not NULL make it NULL
if ($this->con === NULL){
try {
// Establish DSN
$dsn = "mysql:host={$this->host};dbname={$this->database};charset={$this->char}";
// Complete the PDO connection
$this->con = new PDO($dsn, $this->user, $this->pass,$this->opt);
// Return the connection and store it in $con
return $this->con;
// Catch any exceptions and store in $e
} catch(PDOExeption $e){
// Echo error and Exception message
echo "ERROR: " . $e->getMessage(), (int)$e->getCode();
}
// If the try/catch block fails, echo that no connection was established
} else {
echo "ERROR: No connection can be established";
}
}
// Close connection and set it to NULL
public function closeConnection() {
if($this->con !== NULL){
$this->con = NULL;
}
}
// create CRUD subclass (Create, Read, Update, Delete)
}
?>
I changed "db_cred.inc.php" eliminating the array. I may revisit the idea.
<?php
// defining DB Credential CONSTANTS to be stored in variables and instantiated by connect class
define("DB_HOST", "localhost");
define("DB_USER", "user");
define("DB_PASS", "pass");
define("DB_DATABASE", "mytestdb");
define("DB_CHAR", "utf8");
// define an array for db connection.
/*define("DB", [
"DB_HOST" => "localhost",
"DB_USER" => "user",
"DB_PASS" => "pass",
"DB_DATABASE" => "mytestdb",
"DB_CHAR" => "utf8",
]);*/
?>
The error explains itself: You're passing an array where you should be using a string instead.
You need to change this line:
$this->con = new PDO([$this->server, $this->database, $this->user, $this->pass]);
To this, (specifies the DSN first):
$dsn = "mysql:dbname={$this->database};host:{$this->host}";
$this->con = new PDO($dsn, $this->user, $this->password);

unify database initialization in php file

I'm completely new to PHP. I am creating a website.
In several pages, I start my code with :
<?php
$dsn = "mysql:host=localhost;dbname=db;";
$options = [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];
try {
$pdo = new PDO($dsn,'root','', $options);
} catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
//rest of the php + html code here
I would like to unify this code in one php file and call $pdo in every page. But I want to do it in a safe way. Can anyone help.
Better using a singleton for this. This way you avoid opening multiple database connections:
<?php
class Database
{
public static $pdo;
public static function getPDO()
{
if (null === self::$pdo) {
$dsn = "mysql:host=localhost;dbname=db;";
$options = [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];
try {
self::$pdo = new PDO($dsn,'root','', $options);
} catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
}
return self::$pdo;
}
//protected constructor
protected function __construct()
{
}
}
Then use
require_once('path/to/database.php'); //the file with Database class
$pdo = Database::getPDO();
Of course, you need to include this file/class in every page.
Also, isn't a good practice to hardcode your database credentials. Better load from some .env, getenv() or .ini file.
Save your connection code in a file. Let's call it db_connect.php. Then, using the proper path add the following to each file needing a database connection:
include('path/to/db_connect.php');
You may also use include_once(), require() or require_once() depending on what your needs are.

Defining MySQL connection in Slim Framework?

I am hearing great things about Slim Framework- and it seems easy. Except none of the tutorials address where to put the MySQL info.
I see things like $dbCon = getConnection();
But where do I define the username/pw/db/host etc?
First thing first lets open src/settings.php file and configure database connection details to the settings array as shown below.
<?php
return [
'settings' => [
'displayErrorDetails' => true, // set to false in production
// Renderer settings
....
....
// Monolog settings
....
....
// Database connection settings
"db" => [
"host" => "localhost",
"dbname" => "slim3",
"user" => "root",
"pass" => "xxxxx"
],
],
];
There are many database libraries available for PHP, but this example uses PDO. Now open your src/dependencies.php file and configure database library as shown below. you can use your own libraries by adapting the example.
// DIC configuration
$container = $app->getContainer();
...
...
...
// PDO database library
$container['db'] = function ($c) {
$settings = $c->get('settings')['db'];
$pdo = new PDO("mysql:host=" . $settings['host'] . ";dbname=" . $settings['dbname'],
$settings['user'], $settings['pass']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
};
via: https://arjunphp.com/configure-load-database-slim-framework-3/
Its best to keep these credentials in a local configuration file. I add a configs folder outside the web root and add a local.php configuration file to that.
....
/configs
local.php
/public
/vendor
....
You can configure anything you like, but here's the DB:
<?php
// configs/local.php
return array(
'db' => ['user' => 'root', 'password' => 'root']
);
Then include the file in your app and create the connection:
// public/index.php
$config = include(__DIR__ . '/../configs/local.php');
$db = new PDO("mysql:host=localhost;dbname=dbname", $config['db']['user'], $config['db']['password'] );
$app->get('/', function () use ($app, $db) {
// do something with your db connection
});
You can define a function in your file (e.g. index.php)
function getConnection() {
$dbhost="yourdbhost";
$dbuser="yourdbuser";
$dbpass="yourdbpass";
$dbname="yourdb";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
I had great success with this MVC pattern where you store the credentials in a config.php file which gets loaded on every instance of a model: https://github.com/revuls/SlimMVC
You can configure PDO in an external class:
class Connection
{
protected $db;
public function Connection()
{
$conn = NULL;
try{
$conn = new PDO("mysql:host=YOUR_HOST;dbname=DB_NAME;charset=utf8;collation=utf8_unicode_ci", "USER_DB", "PASS_DB");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$this->db = $conn;
}
public function getConnection()
{
return $this->db;
}
}
Then in Slim (Php object oriented):
<?php
class Proxy
{
require_once 'Connection.php';
// init Slim
private $conn = NULL;
// Api Rest code...
# getConnection
public function getConnection(){
if(is_null($this->conn)){
$this->conn = new Connection();
}
return $this->conn->getConnection();
}
Or Php no OO:
<?php
require_once 'Connection.php';
// init Slim
$conn = NULL;
// Api Rest code...
# getConnection
function getConnection(){
global $conn;
if(is_null($conn)){
$conn = new Connection();
}
return $conn->getConnection();
}

PDO Connection MySQL Functions

The code that I will post works but I want to know if it's okay and safe. I will use it to connect my Android APP with my MySQL database.
Here I create the PDO connection. I don't know if I should create it in the construct or using a method. Right now I'm using the connect() method and get() to return the same object. Should I close the connection? Why?
db_config.php
private $db;
function __construct(){
}
function __destruct(){
}
public function connect(){
$host = "XXXXXXXX";
$dbname = "XXXXXXXX";
$username = "XXXXXXX";
$password = "XXXXXXXX";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try{
$this -> db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
} catch (PDOException $ex) {
die("Failed to connect to the database: " . $ex->getMessage());
}
$this-> db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this -> db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $this->db;
}
public function get(){
return $this -> db;
}
trainer_functions.php
In this code I have the functions that I will use to interact with the database. I initialize the connection in the construct and then I use the get() method to return the same connection everytime I need it. Is this okay?
private $db;
function __construct(){
require_once 'db_config.php';
$this->db = new DB_Connect();
$this->db->connect();
}
public function storeUser($json){
$obj = json_decode($json);
$email = $obj -> {"email"};
$pass = $obj -> {"password"
$query = "INSERT INTO USUARIOS (email, pass) VALUES (:email , :pass)";
$query_params = array(
':email' => $email,
':pass' => $pass
);
try {
$stmt = $this -> db -> **get()** -> prepare($query);
$result = $stmt -> execute($query_params);
//json response
}
catch (PDOException $ex) {
//json response
}
The last part of my test code are the calls to the functions using tags. I create a trainer_functions object, then I collect the parameters via POST and call the function with the object. Here I have two questions:
- I send a JSON. Should I send the tag inside or outside the JSON?
- I think here should close the connection because the request has already been completed. It is true?
I would make a good web service because it is the last project of my course and later it will be a personal project with some iOS integration.
Thank you very much.
I've no idea on other files you included (they are too hard to read) but to answer the question from the title: PDO is already a class. You don't need no more.
So, db_config.php
<?php
$host = "XXXXXXXX";
$dbname = "XXXXXXXX";
$username = "XXXXXXX";
$password = "XXXXXXXX";
$charset = 'utf8';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES $charset',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
);
$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset"
$db = new PDO($dsn, $username, $password, $options);
is all you need.

Reusing database connection object

I'm using this function to connect to my MySQL db when needed, and also to re-use the same connection object for any further query I might need in the same php script.
function cnn() {
static $pdo;
if(!isset($pdo)) {
try {
$pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_TIMEOUT, 30);
$pdo->setAttribute(PDO::ATTR_PERSISTENT, true);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
return $pdo;
} catch(PDOException $e) {
http_response_code(503);
echo $e->getCode.': '.$e->getMessage();
die(); //or whatever error handler you use
}
} else {
return $pdo;
}
}
First query (object is created)
echo cnn()->query('SELECT firstname FROM user WHERE id=4;')->fetch(PDO::FETCH_COLUMN)
Second query (object is reused)
echo cnn()->query('SELECT title FROM news WHERE id=516;')->fetch(PDO::FETCH_COLUMN)
Do you agree on this approach? Do you think it can be optimized? Thanks for your opinions.
I agree with the method, though many people will tell you that this "singleton" approach is bad, bad.
However, I disagree with your implementation. It should be:
function cnn() {
static $pdo;
if(!$pdo) {
$conf = array(PDO::ATTR_TIMEOUT => 30,
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME;
$pdo = new PDO($dsn, DB_USER, DB_PASS, $conf);
}
return $pdo;
}
Also, it looks sensible to move handler code into handler (and of course without echoing the error unconditionally!)
function my_exceptionHandler($exception) {
http_response_code(503);
if (ini_get('display_errors')) {
echo $e->getMessage().$e->getTrace();
} else {
log_error($e->getMessage().$e->getTrace());
}
die(); //or whatever error handler you use
}
set_exception_handler("my_exceptionHandler");
Also, I'd extend it to accept a parameter to make several connections possible.

Categories