Advertisement
Guest User

CONEXAO.PHP

a guest
May 17th, 2015
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.01 KB | None | 0 0
  1. <?php
  2.     class Conexao {
  3.         private $data = array();
  4.         //variavel da classe Base
  5.         protected $pdo = null;
  6.  
  7.         public function __set($name, $value){
  8.             $this->data[$name] = $value;
  9.         }
  10.        
  11.         public function __get($name){
  12.             if (array_key_exists($name, $this->data)) {
  13.                 return $this->data[$name];
  14.             }
  15.  
  16.             $trace = debug_backtrace();
  17.             trigger_error(
  18.                 'Undefined property via __get(): ' . $name .
  19.                 ' in ' . $trace[0]['file'] .
  20.                 ' on line ' . $trace[0]['line'],
  21.                 E_USER_NOTICE);
  22.             return null;
  23.         }
  24.  
  25.         //método que retorna a variável $pdo
  26.         public function getPdo() {
  27.             return $this->pdo;
  28.         }
  29.  
  30.         //método construtor da classe
  31.         function __construct($pdo = null) {
  32.             $this->pdo = $pdo;
  33.             if ($this->pdo == null)
  34.                 $this->conectar();
  35.         }
  36.  
  37.         //método que conecta com o banco de dados
  38.         public function conectar() {            
  39.             $local = "localhost";
  40.             $user = "root";
  41.             $pass = "";
  42.             $basename = "diner";
  43.  
  44.             try {
  45.                 $this->pdo = new PDO("mysql:host=$local;dbname=$basename",
  46.                                 "$user",
  47.                                 "$pass",
  48.                                 array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
  49.             } catch (PDOException $e) {
  50.                 print "Error!: " . $e->getMessage() . "<br/>";
  51.                 die();
  52.             }
  53.         }
  54.  
  55.         //método que desconecta
  56.         public function desconectar() {
  57.             $this->pdo = null;
  58.         }  
  59.  
  60.         public function select($statement){
  61.             $pdo = $this->getPdo();  
  62.             $sth = $pdo->prepare($statement);    
  63.             $sth->execute();    
  64.             $result = $sth->fetchAll();  
  65.             return $result;
  66.         }
  67.     }
  68. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement