Advertisement
AlexWebDevelop

DB class

Sep 15th, 2020 (edited)
1,029
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.01 KB | None | 0 0
  1. <?php
  2.  
  3. /* Database class: DB */
  4. class DB
  5. {
  6.   /* PDO resource object */
  7.   private $pdo;
  8.  
  9.   /* Constructor */
  10.   public function __construct(string $host, string $user, string $passwd, string $schema)
  11.   {
  12.     $this->connect($host, $user, $passwd, $schema);
  13.     $this->setParams();
  14.   }
  15.  
  16.   /* Connects to the database */
  17.   private function connect(string $host, string $user, string $passwd, string $schema)
  18.   {
  19.     $this->db = new \PDO('mysql:host=' . $host . ';dbname=' . $schema, $user, $host);
  20.   }
  21.  
  22.   /* Sets some PDO params (exceptions on error and sorting order) */
  23.   private function setParams()
  24.   {
  25.     $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  26.     $this->db->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
  27.   }
  28. }
  29.  
  30.  
  31. /* How to use this class */
  32. $host = 'localhost';
  33. $user = 'user';
  34. $passwd = 'passwd';
  35. $schema = 'mySchema';
  36. $db = NULL;
  37.  
  38. try
  39. {
  40.   $db = new DB($host, $user, $passwd, $schema);
  41. }
  42. catch (PDOException $e)
  43. {
  44.   echo 'PDO connection error.';
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement