Baixe o app para aproveitar ainda mais
Esta é uma pré-visualização de arquivo. Entre para ver o arquivo original
PHP-PDO-Script-01-Mod1.pdf 1 <?php 2 3 //Constantes para armazenamento das variáveis de conexão. 4 define('HOST', '127.0.0.1'); 5 define('DBNAME', 'test'); 6 define('USER', 'user'); 7 define('PASSWORD', 'psswd'); 8 9 //Conectando com o Servidor 10 $conn = mysqli_connect(HOST, USER, PASSWORD, DBNAME) or die( ' Não foi possível conectar.' ); 11 12 //Realizando uma consulta no BD 13 $instrucaoSQL = "Select nome, cpf, telefone From Cliente"; 14 $stmt = mysqli_prepare($conn, $instrucaoSQL); 15 mysqli_stmt_bind_result($stmt, $nome, $cpf, $tel); 16 mysqli_stmt_execute($stmt); 17 18 while (mysqli_stmt_fetch($stmt)) { 19 echo $nome . "\t"; 20 echo $cpf . "\t"; 21 echo $tel . "\n"; 22 } 23 24 //Encerrando a conexão 25 mysqli_close($conn); 26 27 28 PHP-PDO-Script-02-Mod1.pdf 1 <?php 2 3 //Constantes para armazenamento das variáveis de conexão. 4 define('HOST', '127.0.0.1'); 5 define('DBNAME', 'test'); 6 define('USER', 'user'); 7 define('PASSWORD', 'psswd'); 8 9 //Conectando com o Banco de dados 10 $stringConn = "host=".HOST." dbname=".DBNAME." user=".USER." password=".PASSWORD; 11 $conn = pg_connect($stringConn) or die( ' Ocorreu um erro e não foi possível conectar ao banco de dados.' ); 12 13 //Realizando uma consulta no BD 14 $instrucaoSQL = "Select nome, cpf, telefone From Cliente"; 15 $result = pg_query( $conn, $instrucaoSQL ) or die(' Ocorreu um erro na execução da instrução: ' . $instrucaoSQL ); 16 17 //pg_query($dbcon, "SELECT id, nome FROM clientes"); 18 19 //Imprimindo os dados da consulta 20 while ($row = pg_fetch_array( $result )){ 21 echo $row['nome'] . "\t"; 22 echo $row['cpf'] . "\t"; 23 echo $row['telefone'] . "\n"; 24 } 25 26 //Encerrando a conexão 27 pg_close($conn); 28 29 30 PHP-PDO-Script-03-Mod1.pdf 1 <?php 2 3 //Constantes para armazenamento das variáveis de conexão. 4 define('HOST', '127.0.0.1'); 5 define('PORT', '5432'); 6 define('DBNAME', 'test'); 7 define('USER', 'user'); 8 define('PASSWORD', 'psswd'); 9 10 try { 11 $dsn = new PDO("mysql:host=". HOST . ";port=".PORT.";dbname=" . DBNAME . ";user=" . USER . ";password=" . PASSWORD); 12 } catch (PDOException $e) { 13 echo 'A conexão falhou e retornou a seguinte mensagem de erro: ' . $e->getMessage(); 14 } 15 16 17 PHP-PDO-Script-04-Mod1.pdf 1 <?php 2 ... 3 4 try { 5 6 $dsn = new PDO("pgsql:host=". HOST . ";port=".PORT.";dbname=" . DBNAME . ";user=" . USER . ";password=" . PASSWORD, array(PDO::ATTR_PERSISTENT => true)) ; 7 8 } catch (PDOException $e) { 9 echo 'A conexão falhou e retornou a seguinte mensagem de erro: ' . $e->getMessage(); 10 } 11 12 13 PHP-PDO-Script-05-Mod2.pdf 1 <?php 2 class Fruta 3 { 4 //Propriedades ou atributos da Classe 5 var $nome; 6 var $tipo; 7 8 //Construtor da Classe: Essa função é executada todas as vezes em que uma instância da classe é criada. 9 //Como abaixo, essa função pode ser vazia. Ou seja, não realiza nenhuma ação. 10 public function __construct(){ } 11 12 public function setNome($nome) 13 { 14 $this->nome = $nome; 15 } 16 17 public function getNome() 18 { 19 return $this->nome; 20 } 21 22 public function setTipo($tipo) 23 { 24 $this->tipo = $tipo; 25 } 26 27 public function getTipo() 28 { 29 return $this->tipo; 30 } 31 32 } 33 34 35 PHP-PDO-Script-06-Mod2.pdf 1 <?php 2 include "fruta.class.php"; 3 4 $fruta1 = new Fruta(); 5 $fruta1->setNome("morango"); 6 $fruta1->setTipo("vermelha"); 7 8 $fruta2 = new Fruta(); 9 $fruta2->setNome("laranja"); 10 $fruta2->setTipo("cítrica"); 11 12 13 PHP-PDO-Script-07-Mod2.pdf 1 PDO { 2 public __construct ( string $dsn [, string $username [, string $passwd [, array $options ]]] ) 3 public beginTransaction ( void ) : bool 4 public commit ( void ) : bool 5 public errorCode ( void ) : string 6 public errorInfo ( void ) : array 7 public exec ( string $statement ) : int 8 public getAttribute ( int $attribute ) : mixed 9 public static getAvailableDrivers ( void ) : array 10 public inTransaction ( void ) : bool 11 public lastInsertId ([ string $name = NULL ] ) : string 12 public prepare ( string $statement [, array $driver_options = array() ] ) : PDOStatement 13 public query ( string $statement ) : PDOStatement 14 public quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] ) : string 15 public rollBack ( void ) : bool 16 public setAttribute ( int $attribute , mixed $value ) : bool 17 } 18 19 20 PHP-PDO-Script-08-Mod2.pdf 1 PDOStatement implements Traversable { 2 /* Propriedades */ 3 readonly string $queryString; 4 5 /* Métodos */ 6 public bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] ) : bool 7 public bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] ) : bool 8 public bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] ) : bool 9 public closeCursor ( void ) : bool 10 public columnCount ( void ) : int 11 public debugDumpParams ( void ) : void 12 public errorCode ( void ) : string 13 public errorInfo ( void ) : array 14 public execute ([ array $input_parameters = NULL ] ) : bool 15 public fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] ) : mixed 16 public fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] ) : array 17 public fetchColumn ([ int $column_number = 0 ] ) : mixed 18 public fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] ) : mixed 19 public getAttribute ( int $attribute ) : mixed 20 public getColumnMeta ( int $column ) : array 21 public nextRowset ( void ) : bool 22 public rowCount ( void ) : int 23 public setAttribute ( int $attribute , mixed $value ) : bool 24 public setFetchMode ( int $mode ) : bool 25 } 26 27 28 PHP-PDO-Script-09-Mod2.pdf 1 <?php 2 /*a variável $dsn, abaixo, corresponde à instação da classe PDO, inicializada na conexão com o BD*/ 3 4 $qtdeLinhasAfetadas = $dsn->exec("Delete From Cliente Where codigo_cliente = 1"); 5 6 echo "Quantidade de linhas afetadas: " . $qtdeLinhasAfetadas 7 8 9 PHP-PDO-Script-10-Mod2.pdf 1 <?php 2 3 $instrucaoSQL = "Select nome, cpf, telefone From Cliente"; 4 5 //a variável $dsn, abaixo, corresponde à instação da classe PDO, inicializada na conexão com o BD 6 $resultSet = $dsn->query($sql); 7 8 while ($row = $resultSet->fetch()) { 9 echo $row['nome'] . "\t"; 10 echo $row['cpf'] . "\t"; 11 echo $row['telefone'] . "\n"; 12 } 13 14 15 PHP-PDO-Script-11-Mod2.pdf 1 <?php 2 3 //... 4 5 while ($row = $resultSet->fetch(PDO::FETCH_ASSOC)) { 6 //... 7 } 8 9 10 PHP-PDO-Script-12-Mod2.pdf 1 <?php 2 3 //... 4 5 //Realizando uma consulta no BD através do login e senha recebidos por POST 6 $login = $_POST['login']; 7 $pswd = $_POST['pswd']; 8 $instrucaoSQL = "Select * From Usuario Where login = '$login' And password = '$pswd'"; 9 $result = mysql_query( $instrucaoSQL ) or die(' Ocorreu um erro na execução da instrução: ' . $instrucaoSQL . ' ' . mysql_error() ); 10 11 12 PHP-PDO-Script-13-Mod2.pdf 1 <?php 2 3 //... 4 5 //Realizando uma consulta no BD através do login e senha recebidos por POST 6 $login = $_POST['login']; 7 $pswd = $_POST['pswd']; 8 9 $instrucaoSQL = "Select * 10 From Usuario 11 Where 12 login = '' OR true = true;/* 13 And password = '*/--'"; 14 15 //... 16 17 18 PHP-PDO-Script-14-Mod2.pdf 1 <?php 2 3 //Constantes para armazenamento das variáveis de conexão. 4 define('HOST', '127.0.0.1'); 5 define('PORT', '5432'); 6 define('DBNAME', 'test'); 7 define('USER', 'user'); 8 define('PASSWORD', 'psswd'); 9 10 try { 11 $dsn = new PDO("mysql:host=". HOST . ";port=".PORT.";dbname=" . DBNAME . ";user=" . USER . ";password=" . PASSWORD); 12 } catch (PDOException $e) { 13 echo 'A conexão falhou e retorno a seguinte mensagem de erro: ' . $e->getMessage(); 14 } 15 16 //Realizando uma consulta no BD através do login e senha recebidos por POST 17 $login = $_POST['login']; 18 $pswd = $_POST['pswd']; 19 20 $stmt = $dsn->prepare("Select * From Usuario Where login = :login And password = :password"); 21 $stmt->execute([':login' => $login, ':password' => $pswd]); 22 23 /*Aqui entraria o código para tratar o resultado da instrução SQL acima*/ 24 25 26 //Destruindo o objecto statement e fechando a conexão 27 $stmt = null; 28 $dsn = null; 29 30 31 PHP-PDO-Script-15-Mod2.pdf 1 <?php 2 3 //... 4 5 $stmt = $dsn->prepare("Select * From Usuario Where login = ? And password = ?"); 6 $stmt->execute([$login, $pswd]); 7 8 //... 9 10 11 PHP-PDO-Script-16-Mod3.pdf 1 CREATE TABLE cliente ( 2 id_cliente serial NOT NULL, 3 nome_cliente varchar(255), 4 cpf_cliente varchar(11), 5 email_cliente varchar(255), 6 data_nascimento_cliente timestamp, 7 PRIMARY KEY (id_cliente) 8 ); 9 10 11 PHP-PDO-Script-17-Mod3.pdf 1 function validarFormulario(formulario){ 2 3 if(formulario.nome_cliente.value === "" || formulario.nome_cliente.value === null) { 4 alert("O campo Nome não pode ficar vazio."); 5 formulario.nome_cliente.focus(); 6 return false; 7 } 8 9 if(formulario.cpf_cliente.value.length != 11) { 10 alert("O campo CPF precisa ter 11 caracteres."); 11 formulario.cpf_cliente.focus(); 12 return false; 13 } 14 15 //o campo e-mail precisa ser válido, ou seja, deve : "@" e "." 16 if(formulario.email_cliente.value.indexOf("@") == -1 || formulario.email_cliente.value.indexOf(".") == -1) { 17 alert("O campo E-mail não é válido."); 18 formulario.email_cliente.focus(); 19 return false; 20 } 21 22 if(formulario.data_nascimento_cliente.value === "" || formulario.data_nascimento_cliente.value === null) { 23 alert("O campo Data de Nascimento não pode ficar vazio."); 24 formulario.data_nascimento_cliente.focus(); 25 return false; 26 } 27 28 } 29 30 31 PHP-PDO-Script-18-Mod3.pdf 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Formulário HTML - Cadastro de Clientes</title> 5 <meta charset="utf-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <!-- Bootstrap --> 9 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" /> 10 </head> 11 <body> 12 13 <div class="container"> 14 <div class="row"> 15 <div class="col-md-12"> 16 <form action="processa_cliente.php" method="post"> 17 <div class="row"> 18 <div class="col-md-8"> 19 <div class="card"> 20 <div class="card-header"> 21 <h3>Cadastro de Clientes</h3> 22 </div> 23 <div class="card-body"> 24 <div class="form-group"> 25 <label for="nome_cliente">Nome</label> 26 <input type="text" class="form-control" id="nome_cliente" name="nome_cliente" placeholder="Seu nome" required> 27 </div> 28 <div class="form-group"> 29 <label for="cpf_cliente">CPF</label> 30 <input type="text" class="form-control" minlength="11" maxlength="11" id="cpf_cliente" 31 name="cpf_cliente" placeholder="Seu CPF" title="Digite apenas números" required> 32 </div> 33 <div class="form-group"> 34 <label for="email_cliente">Endereço de E-mail</label> 35 <input type="email" class="form-control" id="email_cliente" name="email_cliente" aria-describedby="emailHelp" 36 placeholder="Seu e-mail" required> 37 <small id="emailHelp" class="form-text text-muted">Nunca vamos compartilhar seu email, com ninguém.</small> 38 </div> 39 <div class="form-group"> 40 <label for="data_nascimento_cliente">Data de Nascimento</label> 41 <input type="date" class="form-control" id="data_nascimento_cliente" name="data_nascimento_cliente" 42 placeholder="Sua data de nascimento" required> 43 </div> 44 <div class="form-group text-center"> 45 <button type="submit" class="btn btn-primary">Enviar</button> 46 </div> 47 </div> 48 </div> 49 </div> 50 </div> 51 </form> 52 </div> 53 </div> 54 </div> 55 56 <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> 57 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> 58 </body> 59 </html> 60 61 62 PHP-PDO-Script-19-Mod3.pdf 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>Formulário HTML - Cadastro de Clientes</title> 5 <meta charset="utf-8"> 6 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" /> 7 <script type="text/javascript"> 8 function validarFormulario(formulario){ 9 //o código da função está no tópico “Validação no lado Cliente – Javascript” 10 } 11 </script> 12 </head> 13 <body> 14 <div class="container"> 15 <div class="row"> 16 <div class="col-md-12"> 17 <form action="processa_cliente.php" name="form_clientes" method="post" onsubmit="return validarFormulario(this);"> 18 <div class="row"> 19 <div class="col-md-8"> 20 <div class="card"> 21 <div class="card-header"> 22 <h3>Cadastro de Clientes</h3> 23 </div> 24 <div class="card-body"> 25 <div class="form-group"> 26 <label for="nome_cliente">Nome</label> 27 <input type="text" class="form-control" id="nome_cliente" name="nome_cliente" placeholder="Seu nome" > 28 </div> 29 <div class="form-group"> 30 <label for="cpf_cliente">CPF</label> 31 <input type="text" class="form-control" id="cpf_cliente" name="cpf_cliente" placeholder="Seu CPF" title="Digite apenas números" > 32 </div> 33 <div class="form-group"> 34 <label for="email_cliente">Endereço de E-mail</label> 35 <input type="text" class="form-control" id="email_cliente" name="email_cliente" placeholder="Seu e-mail" > 36 </div> 37 <div class="form-group"> 38 <label for="data_nascimento_cliente">Data de Nascimento</label> 39 <input type="text" class="form-control" id="data_nascimento_cliente" name="data_nascimento_cliente" placeholder="Sua data de nascimento" > 40 </div> 41 <div class="form-group text-center"> 42 <button type="submit" class="btn btn-primary">Enviar</button> 43 </div> 44 </div> 45 </div> 46 </div> 47 </div> 48 </form> 49 </div> 50 </div> 51 </div> 52 <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> 53 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> 54 </body> 55 </html> 56 57 58 PHP-PDO-Script-20-Mod3.pdf 1 <?php 2 /***VALIDAÇÃO DOS DADOS RECEBIDOS DO FORMULÁRIO ***/ 3 if($_REQUEST['nome_cliente'] == ""){ 4 echo "O campo Nome não pode ficar vazio."; 5 exit; 6 } 7 8 if(strlen($_REQUEST['cpf_cliente']) != 11){ 9 echo "O campo CPF precisa ter 11 caracteres."; 10 exit; 11 } 12 13 if(!stripos($_REQUEST['email_cliente'], "@") || !stripos($_REQUEST['email_cliente'], ".")){ 14 echo "O campo E-mail não é válido."; 15 exit; 16 } 17 18 if($_REQUEST['data_nascimento_cliente'] == ""){ 19 echo "O campo Data de Nascimento não pode ficar vazio."; 20 exit; 21 } 22 /***FIM DA VALIDAÇÃO DOS DADOS RECEBIDOS DO FORMULÁRIO ***/ 23 24 25 /***CONEXÃO COM O BD ***/ 26 //Constantes para armazenamento das variáveis de conexão. 27 define('HOST', '192.168.52.128'); 28 define('PORT', '5432'); 29 define('DBNAME', 'minimundo'); 30 define('USER', 'postgres'); 31 define('PASSWORD', '159753'); 32 33 try { 34 $dsn = new PDO("pgsql:host=". HOST . ";port=".PORT.";dbname=" . DBNAME . ";user=" . USER . ";password=" . PASSWORD); 35 } catch (PDOException $e) { 36 echo 'A conexão falhou e retorno a seguinte mensagem de erro: ' . $e->getMessage(); 37 } 38 /*** FIM DOS CÓDIGOS DE CONEXÃO COM O BD ***/ 39 40 41 /***PREPARAÇÃO E INSERÇÃO NO BANCO DE DADOS ***/ 42 $stmt = $dsn->prepare("INSERT INTO 43 cliente(nome_cliente, cpf_cliente, email_cliente, data_nascimento_cliente) 44 VALUES (?, ?, ?, ?) 45 "); 46 47 $resultSet = $stmt->execute([$_REQUEST['nome_cliente'], $_REQUEST['cpf_cliente'], $_REQUEST['email_cliente'], $_REQUEST['data_nascimento_cliente']]); 48 49 if($resultSet){ 50 echo "Os dados foram inseridos com sucesso."; 51 }else{ 52 echo "Ocorreu um erro e não foi possível inserir os dados."; 53 } 54 55 //Destruindo o objecto statement e fechando a conexão 56 $stmt = null; 57 $dsn = null; 58 59 60 PHP-PDO-Script-21-Mod3.pdf 1 <?php 2 /***CONEXÃO COM O BD ***/ 3 //O código de validação server side pode ser visto no exemplo de código 3. 4 //Constantes para armazenamento das variáveis de conexão. 5 define('HOST', '192.168.52.128'); 6 define('PORT', '5432'); 7 define('DBNAME', 'minimundo'); 8 define('USER', 'postgres'); 9 define('PASSWORD', '159753'); 10 try { 11 $dsn = new PDO("pgsql:host=". HOST . ";port=".PORT.";dbname=" . DBNAME . ";user=" . USER . ";password=" . PASSWORD); 12 } catch (PDOException $e) { 13 echo 'A conexão falhou e retorno a seguinte mensagem de erro: ' . $e->getMessage(); 14 } 15 /***PREPARAÇÃO E INSERÇÃO NO BANCO DE DADOS ***/ 16 $instrucaoSQL = "Select id_cliente, nome_cliente, cpf_cliente, email_cliente, data_nascimento_cliente From cliente"; 17 $resultSet = $dsn->query($instrucaoSQL); 18 ?> 19 <!DOCTYPE html> 20 <html> 21 <head> 22 <title>Formulário HTML - Cadastro de Clientes</title> 23 <meta charset="utf-8"> 24 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 25 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 26 <!-- Bootstrap --> 27 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" /> 28 </head> 29 <body> 30 <div class="container"> 31 <div class="row"> 32 <div class="col-md-12"> 33 <div class="row"> 34 <div class="col-md-8"> 35 <div class="card"> 36 <div class="card-header"> 37 <h3>Listagem de Clientes</h3> 38 </div> 39 <div class="card-body"> 40 <table class="table"> 41 <thead class="thead-dark"> 42 <tr> 43 <th scope="col">#</th> 44 <th scope="col">Nome</th> 45 <th scope="col">CPF</th> 46 <th scope="col">E-mail</th> 47 <th scope="col">Data de Nascimento</th> 48 </tr> 49 </thead> 50 <tbody> 51 <?php 52 while ($row = $resultSet->fetch(PDO::FETCH_ASSOC)): 53 ?> 54 <tr> 55 <th scope="row"><?php echo $row['id_cliente']; ?></th> 56 <td><?php echo $row['nome_cliente']; ?></td> 57 <td><?php echo preg_replace("/(\d{3})(\d{3})(\d{3})(\d{2})/", "\$1.\$2.\$3-\$4", $row['cpf_cliente']); ?></td> 58 <td><?php echo $row['email_cliente']; ?></td> 59 <td><?php echo date('d/m/Y', strtotime($row['data_nascimento_cliente'])); ?></td> 60 </tr> 61 <?php 62 endwhile; 63 ?> 64 </tbody> 65 </table> 66 </div> 67 </div> 68 </div> 69 </div> 70 </div> 71 </div> 72 </div> 73 <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> 74 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></scr ipt> 75 </body> 76 </html> 77 78 79
Compartilhar