Advertisement
Guest User

Untitled

a guest
Dec 14th, 2016
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 3.02 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Conn.class [ CONEXÃO ]
  5.  * Classe abstrata de conexão. Padrão SingleTon.
  6.  * Retorna um objeto PDO pelo método estático getConn();
  7.  */
  8. abstract class Conn {
  9.  
  10.     private static $Host = HOST;
  11.     private static $User = USER;
  12.     private static $Pass = PASS;
  13.     private static $Dbsa = DBSA;
  14.  
  15.     /** @var PDO */
  16.     private static $Connect = null;
  17.  
  18.     /**
  19.      * Conecta com o banco de dados com o pattern singleton.
  20.      * Retorna um objeto PDO!
  21.      */
  22.     private static function Conectar() {
  23.         try {
  24.             if (self::$Connect == null):
  25.                 $dsn = 'mysql:host=' . self::$Host . ';dbname=' . self::$Dbsa;
  26.                 $options = [ PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'];
  27.                 self::$Connect = new PDO($dsn, self::$User, self::$Pass, $options);
  28.             endif;
  29.         } catch (PDOException $e) {
  30.             PHPErro($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
  31.             die;
  32.         }
  33.  
  34.         self::$Connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  35.         return self::$Connect;
  36.     }
  37.  
  38.     /** Retorna um objeto PDO Singleton Pattern. */
  39.     protected static function getConn() {
  40.         return self::Conectar();
  41.     }
  42.  
  43. }
  44.  
  45.  
  46. <!DOCTYPE html>
  47. <html lang="pt-br">
  48.     <head>
  49.         <meta charset="UTF-8">
  50.         <title>Prepared Statements</title>
  51.     </head>
  52.     <body>
  53.         <?php
  54.         require('../07-php-data-object/_app/Config.inc.php');
  55.        
  56.         //nossa classe de conexão
  57.         $PDO = new Conn; //NÃO DEIXA INSTANCIAR A CLASSE POR SER ABSTRACT!!! POR QUE???
  58.         $name = "Firefox";
  59.         $views = '128';
  60.        
  61.         //vamos manipular a tabela ws_siteviews_agent
  62.         try{
  63.            
  64.             //cadastro no banco ---> quando passamos ? nos inserts,
  65.             //é como se tivessemos informando que vão ser passados para a query
  66.             $QRCreate = "INSERT INTO ws_siteviews_agent (agent_name, agent_views) VALUES (?, ?)";
  67.            
  68.             $Create = $PDO->getConn()->prepare($QRCreate);
  69.            
  70.            
  71.             //informar a inserção de dados. O 3o parâmetro não é obrigatório,
  72.             //o bind value reconhece o conteúdo sempre como uma string. Se não
  73.             //for informado e passarmos um INT no lugar do chrome, ele passa como string
  74.             //do mesmo jeito
  75.             //*** ---> 1 quer dizer que estamos passando a primeira interrogação (primeira coluna)
  76.             $Create->bindValue(1, 'Chrome', PDO::PARAM_STR);
  77.            
  78.             $Create->bindValue(2, '122', PDO::PARAM_INT);
  79.            
  80.             $Create->execute();
  81.            
  82.             if($Create->rowCount()):
  83.                 echo "{$PDO->getConn()->lastInsertId()} - Cadastro com sucesso!<hr>";
  84.             endif;
  85.                                    
  86.         } catch (Exception $e) {
  87.             PhpErro($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
  88.         }
  89.        
  90.        
  91.         ?>
  92.     </body>
  93. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement