haikelfazzani

PHP OOP : HOW TO CONNECT TO A DATABASE

Aug 19th, 2017
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.73 KB | None | 0 0
  1. <?php
  2.  
  3.     // database named : ' php_tut '
  4.     // connection to database : Object-Oriented Programming
  5.    
  6.     class connectDb{
  7.  
  8.         private $serverNme = "localhost";
  9.         private $dbName = "php_tut";
  10.         private $dbUser = "root";
  11.         private $dbPassword = "";
  12.         private $conn = false;
  13.  
  14.         function connect(){
  15.  
  16.             try{
  17.             $this->conn = new PDO("mysql:host=$this->serverNme;dbname=$this->dbName",
  18.                 $this->dbUser,$this->dbPassword);
  19.  
  20.             return $this->conn;
  21.  
  22.             }catch(PDOException $e){
  23.  
  24.                 echo "error" . $e->getMessage();
  25.  
  26.             }
  27.  
  28.         }
  29.  
  30.         function disconnect(){  // you will need this function later to close connection
  31.             $this->conn = NULL;
  32.             return $this->conn;
  33.         }
  34.  
  35.     }
  36.  
  37.     $connection = new connectDb();
  38.     echo $connection->connect();
Advertisement
Add Comment
Please, Sign In to add comment