Advertisement
Guest User

DB connect

a guest
Sep 19th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.88 KB | None | 0 0
  1. <?php
  2.  
  3. class DB
  4. {
  5.     private $link;
  6.  
  7.     public function __construct()
  8.     {
  9.         $this->connect();
  10.     }
  11.  
  12.     private function connect()
  13.     {
  14.         $config = require_once 'config.php';
  15.  
  16.         $dsn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['db_name'] . ';charset =' . $config['charset'];
  17.  
  18.         $this->link = new PDO($dsn, $config['username'], $config['password']);
  19.  
  20.         return $this;
  21.     }
  22.  
  23.     public function execute($sql)
  24.     {
  25.         $sth = $this->link->prepare($sql);
  26.  
  27.         return $sth->execute();
  28.     }
  29.  
  30.     public function query($sql)
  31.     {
  32.         $exe = $this->execute($sql);
  33.  
  34.         $result = $exe->fetchAll(PDO::FETCH_ASSOC);
  35.  
  36.         if ($result == false) {
  37.             return [];
  38.         }
  39.         return $result;
  40.     }
  41. }
  42.  
  43. $db = new DB();
  44.  
  45. $db->execute("INSERT INTO charz SET name='MadDog', health='100'");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement