Advertisement
dhtmlextreme

How To Use PDO to connect to mysql

Jan 21st, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.30 KB | None | 0 0
  1. <?php
  2. class connect{
  3.          public $db_host= "localhost"; //database host e.g. localhost,127.0.0.1
  4.          public $username="admin";     //username of sql server
  5.          public $password= "pass";     //password of sql server
  6.          public $db_name="dbtest";     //name of existing database on server
  7.  
  8.          private $dbc=null;  //database identifier
  9.    
  10.     function __construct(){
  11.         try{
  12.             $this->dbc= new PDO("mysql:host=$this->db_host; dbname=$this->db_name", $this->username, $this->password);
  13.         }
  14.         catch (PDOException $e){
  15.             $this->dbc=null;
  16.             echo 'Connection failed: ' . $e->getMessage();
  17.             exit();
  18.            }
  19.     }
  20.  
  21.     /*
  22.      * To run this tester, make sure your database contains a table called users with a field called email with at least one value
  23.      *
  24.      */
  25.      public function tester2(){
  26.          $result = $this->dbc->query("SELECT * FROM `users` ", PDO::FETCH_ASSOC);
  27.          foreach($result as $row) {
  28.                 var_dump($row);
  29.          }
  30.     }
  31.    
  32.     /*
  33.      * You do not need any table to test this one
  34.      */
  35.     public function tester(){
  36.         $result = $this->dbc->query("SELECT 1+1 FROM `users` ", PDO::FETCH_ASSOC);
  37.         foreach($result as $row) {
  38.             var_dump($row);
  39.         }
  40.     }
  41. }
  42.  
  43. $connection = new connect();
  44.  
  45. $connection->tester();
  46.  
  47. $connection->tester2();
  48.  
  49. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement