Advertisement
Guest User

Untitled

a guest
Aug 18th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.48 KB | None | 0 0
  1. <?php  
  2.     class pdo_handler{
  3.    
  4.         public $DBH;
  5.    
  6.         //Connection, MIGHT OUTSOURCE IT TO INDIA (aka another file).
  7.         public function __construct(){
  8.             $host = 'localhost';
  9.             $dbname = 'wedding';
  10.             $user = 'root';
  11.             $pass = 'root';
  12.            
  13.             try{
  14.             //MySQL with PDO_MYSQL  
  15.               $this->DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
  16.            
  17.             }catch(PDOException $e){
  18.                 echo $e->getMessage();
  19.             }
  20.    
  21.         }
  22.        
  23.         //Function to insert data, takes an associative array, builds a strings to insert data securely using PDO in the table specified.
  24.         public function insert($array, $table){
  25.             $string = '';
  26.            
  27.             foreach($array as $key => $value){
  28.                 $string .=  ":" . $key . ", ";
  29.             }
  30.            
  31.             $string =  substr($string, 0, -2);
  32.            
  33.             $STH = $this->DBH->prepare("INSERT INTO $table values(" . $string . ")");
  34.             $STH->execute($array);
  35.            
  36.         }
  37.        
  38.         //Select function returns an array with all the rows affected, each array has all the column names requested, also returns the [rows] affected.
  39.         public function select($what, $where){         
  40.             $i = 0;
  41.             $data = array();
  42.            
  43.             $STH = $this->DBH->query("SELECT $what from $where");
  44.             $STH->setFetchMode(PDO::FETCH_ASSOC);
  45.            
  46.             while($row = $STH->fetch()){
  47.                 foreach($row as $key => $value){
  48.                     $data[$i][$key] = $value;
  49.                 }
  50.                 $i++;
  51.             }
  52.             $data['rows'] = $i;
  53.             return $data;
  54.         }
  55.        
  56.     }
  57.    
  58. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement