X
    Categories: PHP

php pdo database connection class

php pdo database connection class

In this tutorial, we are going to see how to connect pdo database connection class using php. PDP – PHP Database Object – is a database access layer which providing a common method to access multiple databases. In present days PHP with Mysql connections are after deprecated. We should go with Mysqli or PDO [ PHP database object ]. My suggestions is to go with PDO because now a days new frameworks  using PDO database conncetions only. There are list of features in PDO

Features in PDO

  • 1. Driver for twelve different databases
    2. OOPS concept
    3. Named Parameters
    4. Stored procedures and Functions
    5. Quick response
    6. Bind and Prepare statements

Step 1 : Create a database class and connect host & database

My Host : Localhost
My Database : sample
My Database Username : root
My Database Password : root
$conn is user defined variable to access database connection.

Example :


Db.inc.php

<?php 
class Database {

	public $conn;
	private $engine;
	private $host;
	private $username;
	private $database;
	private $password;

	public function __construct() {

		$this->engine 	= 'mysql';
		$this->host 	= 'localhost';
		$this->database = 'vue_js';
		$this->username = 'root';
		$this->password = 'root';
		$dns = $this->engine . ":" . "host=" . $this->host . ";dbname=" . $this->database ;

		try {
			$this->conn = new \PDO($dns, $this->username, $this->password);
		}
		catch ( PDOException $e ) {
			$e->getMessage();
		}
		if($this->conn) {
			return $this->conn;
		}
	}

}

Step 2 : Extend your database class to access

<?php

require_once( 'Db.inc.php' );

class Functions extends Database {

	public $conn;

	public function __construct()
	{
		$this->conn = parent::__construct();
	}

	public function fetchAll('users')
	{
		$query = "Select * from $table";
		$stmt =  $this->conn->prepare($query);
		$stmt->execute();
		return $stmt->fetchAll();
	}

}

Declare user defined value globally : $conn.

Connect your parent class database with current class.

$this->conn = parent::__construct();

First step is to prepare the query $this->conn->prepare(“Select * from users”); and stored in in variable

Second step is to execute the prepared query. $stmt->execute();

Here you can find some basic PDO functions like insert, update, edit, delete.

Hope it will help someone.

If you like this article don’t forget to share and comment.

Marimuthu: