Skip to main content

Create PHP PDO wrapper class

Create PHP PDO wrapper class

Step 1: Create Config file config.php
<?php

ini_set("display_errors", 1);  
define('DB_HOST', "localhost");
define('DB_NAME', "pdoTest");
define('DB_USER', "root");
define('DB_PASS', "root");
?>


Step 2: Now create wrapper class Database.php
<?php class Database {

    private $conn;
private $stmt;

    function __construct(){ 
include_once 'config.php';
try{
$this->conn = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME."", DB_USER, DB_PASS); 
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $this->conn;
}catch(PDOException $e){
            return $e->getMessage();
        }
}
public function query($query){
$query = trim($query);
try {
$this->stmt = $this->conn->prepare($query);
return $this;
}catch (PDOException $e) {
return $e->getMessage();
}
}
public function execute(){
return $this->stmt->execute();
}
public function deleteQuery($query)
{
$this->query($query);
$this->execute();
return $this->affected_rows();
}
public function resultset() {
        $this->execute();
        return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
    }
public function rowCount()
{
$this->execute();
        return $this->stmt->rowCount();
}
public function insertTable($table,$values,$return_id=TRUE){
if(!is_array($values)){
return FALSE;
}
$table = preg_replace('/[^\da-z_]/i', '', $table);
$fld = $vals = array();

foreach($values as $k=>$v){
$fld[]= "`$k`=?";
$vals[]= trim($v);
}
$set = implode(',', $fld);
$qry = "INSERT INTO `$table` SET $set";
try {
$this->query($qry);
$this->stmt->execute($vals);
return $this->dbh->lastInsertId();
}catch (PDOException $e) {
return $e->getMessage();
}
}
public function single() {
        $this->execute();
        return $this->stmt->fetch();
    }
public function affected_rows(){
        return $this->stmt ? $this->stmt->rowcount() : false;
    }
public function update($table, array $fields, $cond){
$table = preg_replace('/[^\da-z_]/i', '', $table);
$query = "UPDATE `$table` SET";
$values = array();
foreach ($fields as $name => $value) {
$query .= ' '.$name.' = :'.$name.','; // the :$name part is the placeholder, e.g. :zip
$values[':'.$name] = $value; // save the placeholder
}
$condition = (isset($cond))?" Where $cond":'';
$query = substr($query, 0, -1).$condition.';'; // remove last , and add a ;
try {
$this->query($query);
$this->stmt->execute($values);
return $this->affected_rows();
}catch (PDOException $e) {
return $e->getMessage();
}
}
public function closeConnection(){
try {
            $this->conn = null; //Closes connection
        } catch(PDOException $e) {
return $e->getMessage();  
        }
}

} ?>

Step 3: Now create index.php file and access result.
<?php 
include_once 'Database.php';
$db_conntect = new Database();

// Select Query
$result = $db_conntect->query("Select * from menus")->resultset();
echo "<pre>"; print_r($result);

//Insert Query
$userArray = array('username'=>'sudhir','email'=>'sudhir@xyz.com','password'=>'123456');
$db->insertTable('admin',$userArray);

//Update Query
$updateArray = array('email'=>'sudhir@xyz.com');
$condition = "username='admin'";
$db->update('admin',$updateArray,$condition);


// Create query, bind values and return a single row.
$row = $db->query('SELECT col1, col2, col3 FROM mytable WHERE id > ? LIMIT ?')
   ->bind(1, 2)
   ->bind(2, 1)
   ->single();

// Update the LIMIT and get a resultset.
$db->bind(2,2);
$rs = $db->resultset();
   

?>

Comments

  1. Creating a PHP PDO wrapper class can help simplify database interactions and promote reusable code.

    The class also supports transactions, which can be useful for ensuring data integrity:

    Final Year Project Centers in Chennai

    IEEE projects for cse

    beginTransaction();

    // Perform multiple queries here
    $db->query('INSERT INTO users (name, email) VALUES (:name, :email)');
    $db->bind(':name', 'Alice');
    $db->bind(':email', 'alice@example.com');
    $db->execute();

    $db->query('INSERT INTO orders (user_id, product) VALUES (:user_id, :product)');
    $db->bind(':user_id', $db->lastInsertId());
    $db->bind(':product', 'Product 1');
    $db->execute();

    $db->endTransaction();
    } catch (Exception $e) {
    $db->cancelTransaction();
    echo 'Transaction failed: ' . $e->getMessage();
    }
    ?>

    ReplyDelete

Post a Comment

Popular posts from this blog

A Guide to UTF-8 for PHP and MySQL

Data Encoding: A Guide to UTF-8 for PHP and MySQL As a MySQL or PHP developer, once you step beyond the comfortable confines of English-only character sets, you quickly find yourself entangled in the wonderfully wacky world of UTF-8. On a previous job, we began running into data encoding issues when displaying bios of artists from all over the world. It soon became apparent that there were problems with the stored data, as sometimes the data was correctly encoded and sometimes it was not. This led programmers to implement a hodge-podge of patches, sometimes with JavaScript, sometimes with HTML charset meta tags, sometimes with PHP, and soon. Soon, we ended up with a list of 600,000 artist bios with double- or triple encoded information, with data being stored in different ways depending on who programmed the feature or implemented the patch. A classical technical rat’s nest.Indeed, navigating through UTF-8 related data encoding issues can be a frustrating and hair-pul...

How To Create Shortcodes In WordPress

We can create own shortcode by using its predified hooks add_shortcode( 'hello-world', 'techsudhir_hello_world_shortcode' ); 1. Write the Shortcode Function Write a function with a unique name, which will execute the code you’d like the shortcode to trigger: function techsudhir_hello_world_shortcode() {    return 'Hello world!'; } Example: [hello-world] If we were to use this function normally, it would return Hello world! as a string 2. Shortcode function with parameters function techsudhir_hello_world_shortcode( $atts ) {    $a = shortcode_atts( array(       'name' => 'world'    ), $atts );    return 'Hello ' . $a['name'] . !'; } Example: [hello-world name="Sudhir"] You can also call shortcode function in PHP using do_shortcode function Example: do_shortcode('[hello-world]');

How to replace plain URLs with links

Here we will explain how to replace Urls with links from string Using PHP $string ='Rajiv Uttamchandani is an astrophysicist, human rights activist, and entrepreneur. Academy, a nonprofit organization dedicated to providing a robust technology-centered education program for refugee and displaced youth around the world.  CNN Interview - https://www.youtube.com/watch?v=EtTwGke6Jtg   CNN Interview - https://www.youtube.com/watch?v=g7pRTAppsCc&feature=youtu.be'; $string = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $string); Using Javascript <script> function linkify(inputText) {     var replacedText, replacePattern1, replacePattern2, replacePattern3;     //URLs starting with http://, https://, or ftp://     replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;     replacedText = inputT...