logo
Blog single photo

how to connect database using pdo


                        

<?php
    class Database
    {
    private static $dbname='databasename';
    private static $dbhost='localhost';
    private static $dbusername='user';
    private static $dbuserpassword='password';
   
    private static $cont= null;
   
    public function __construct(){
        die('init function not access');
       
        }
       
        public static function connect(){
            if(null== self::$cont)
            {
            try
            {
            self::$cont= new PDO("mysql:host=".self::$dbhost.";" ."dbname=".self::$dbname,
            self::$dbusername,self::$dbuserpassword);   
            }
           
            catch (PDOException $e)
            {
                die($e->getMessage());
            }
            }
            return self::$cont;
           
            }
           
            public static function disconnect()
            {
            self::$cont=null;   
            }
   
    }
   
    ?>

See Example..

<?php
$pdo= Database::connect();
$sql="select * from table where ID=:UID";

$data= $pdo->prepare($sql);
$data->execute(array(':UID' => $_SESSION['ID']));
$post = $data->fetch();

if($post){

foreach($post as $postdata ){ ?>

<h1><?php  echo $postdata['username'] ; ?></h1>

<?php

}
}
?>

Top