How to use PDO in php? Reviewed by Momizat on . PDO (PHP Data Objects) is a general database abstraction layer with support 12 different drivers.it's connection is easy and performance is fast. mypdo.php [php PDO (PHP Data Objects) is a general database abstraction layer with support 12 different drivers.it's connection is easy and performance is fast. mypdo.php [php Rating: 0

How to use PDO in php?

PDO (PHP Data Objects) is a general database abstraction layer with support 12 different drivers.it’s connection is easy and performance is fast.

mypdo.php

<?php 
define('SERVER','XXXXXXXXX');
define('DB_USER','XXXXXXXXXXXXX');
define('DB_PASS','XXXXXXXXXXX');
define('DB_NAME','XXXXXXXXX');
define('DB_DRIVER','mysql');

class Mypdo extends PDO{
	function __construct() {
        parent::__construct(DB_DRIVER.":host=".SERVER.";dbname=".DB_NAME,DB_USER,DB_PASS);
   }
   private function updatedataque($arr) {
		$str="";
		if(!empty($arr) && is_array($arr)){
			foreach ($arr as $arrkey=>$arrvalue)	{
				$str.=$arrkey.'='."'".$arrvalue."',";				
			}
			return substr($str,0,-1);	
		}
		return 0;
	}
   function insertdata($tbl,$data){
	   $substr=$this->updatedataque($data);
	   $this->exec("insert into ".$tbl." SET ".$substr);
	   return $this->lastInsertId();
	}
	function updatedata($tbl,$data,$fld,$fldvalue){
	   $substr=$this->updatedataque($data);	   
	   return $this->exec("UPDATE ".$tbl." SET ".$substr." where ".$fld."="."'".$fldvalue."'");	     
	}
	function deletedata($tbl,$fld,$fldvalue){	   	   
	   return $this->exec("DELETE from ".$tbl." where ".$fld."="."'".$fldvalue."'");	     
	}
	function fetchdata($query){
		$result=$this->query($query);	   	   
	   $result->setFetchMode(PDO::FETCH_ASSOC);
	   return $result;	   	     
	}
		 
}
$db=new Mypdo(); 
?>

Use of PDO

<?php 
include "mypdo.php";

#for insertion operation
$frmd=array('name'=>'manish',........);
$db->insertdata("tblname",$frmd);
#for update operation

$frmd=array('name'=>'manish',........);
$db->updatedata("user",$frmd,'user_id','1');

#for delete operation 
$db->deletedata("user",'user_id','1');

#for lastInsertId
$db->lastInsertId();

#for count row 
$cnt=$result->rowCount();

#for fetch data from table

$query="SELECT * FROM user limit 5";
$result =$db->fetchdata($query);
echo $cnt=$result->rowCount();
while($user = $result->fetch()){
print_r($user);
}
?>

Leave a Comment

© 2014 Powered By