Skorpius

PDO Connection with options

Jun 13th, 2022 (edited)
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.02 KB | None | 0 0
  1. <?php
  2.  
  3.     //This script, in some cases, may cause issues with the options. If things are not working as expected then comment out the 2nd option,
  4.     // \PDO::ATTR_DEFAULT_FETCH_MODE and try testing your project again.
  5.  
  6.     $DB_HOST  = 'localhost';
  7.     $DB_LOGIN = 'root';
  8.     $DB_PASS  = 'password';
  9.     $DB_NAME  = 'Your_Database_Name';
  10.     $charset  = 'utf8mb4';
  11.  
  12.     $options = [
  13.         \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
  14.         \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  15.         \PDO::ATTR_EMULATE_PREPARES => false,
  16.     ];
  17.  
  18.     $dsn = "";
  19.  
  20.     try{
  21.        
  22.         $dsn = "mysql:host=$DB_HOST;dbname=$DB_NAME;charset=$charset";
  23.  
  24.         $pdo = new PDO($dsn, $DB_LOGIN,$DB_PASS,$options);
  25.  
  26.         $connected = "<hr><p>Connected to the ".$DB_NAME." database</p>";
  27.         echo $connected; //Echo this var, and the line above, out of your code when in production. This is only to test connection
  28.  
  29.     }catch(PDOException $e){
  30.  
  31.         die ('Connection Failed: '.$e->getMessage());
  32.  
  33.     }
Advertisement
Add Comment
Please, Sign In to add comment