Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Conn.class [ CONEXÃO ]
- * Classe abstrata de conexão. Padrão SingleTon.
- * Retorna um objeto PDO pelo método estático getConn();
- */
- abstract class Conn {
- private static $Host = HOST;
- private static $User = USER;
- private static $Pass = PASS;
- private static $Dbsa = DBSA;
- /** @var PDO */
- private static $Connect = null;
- /**
- * Conecta com o banco de dados com o pattern singleton.
- * Retorna um objeto PDO!
- */
- private static function Conectar() {
- try {
- if (self::$Connect == null):
- $dsn = 'mysql:host=' . self::$Host . ';dbname=' . self::$Dbsa;
- $options = [ PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'];
- self::$Connect = new PDO($dsn, self::$User, self::$Pass, $options);
- endif;
- } catch (PDOException $e) {
- PHPErro($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
- die;
- }
- self::$Connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- return self::$Connect;
- }
- /** Retorna um objeto PDO Singleton Pattern. */
- protected static function getConn() {
- return self::Conectar();
- }
- }
- <!DOCTYPE html>
- <html lang="pt-br">
- <head>
- <meta charset="UTF-8">
- <title>Prepared Statements</title>
- </head>
- <body>
- <?php
- require('../07-php-data-object/_app/Config.inc.php');
- //nossa classe de conexão
- $PDO = new Conn; //NÃO DEIXA INSTANCIAR A CLASSE POR SER ABSTRACT!!! POR QUE???
- $name = "Firefox";
- $views = '128';
- //vamos manipular a tabela ws_siteviews_agent
- try{
- //cadastro no banco ---> quando passamos ? nos inserts,
- //é como se tivessemos informando que vão ser passados para a query
- $QRCreate = "INSERT INTO ws_siteviews_agent (agent_name, agent_views) VALUES (?, ?)";
- $Create = $PDO->getConn()->prepare($QRCreate);
- //informar a inserção de dados. O 3o parâmetro não é obrigatório,
- //o bind value reconhece o conteúdo sempre como uma string. Se não
- //for informado e passarmos um INT no lugar do chrome, ele passa como string
- //do mesmo jeito
- //*** ---> 1 quer dizer que estamos passando a primeira interrogação (primeira coluna)
- $Create->bindValue(1, 'Chrome', PDO::PARAM_STR);
- $Create->bindValue(2, '122', PDO::PARAM_INT);
- $Create->execute();
- if($Create->rowCount()):
- echo "{$PDO->getConn()->lastInsertId()} - Cadastro com sucesso!<hr>";
- endif;
- } catch (Exception $e) {
- PhpErro($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
- }
- ?>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement