web training aula 02: introduction to php

40
The image part with relationshi p ID rId14 was not found in the file. The image part with relationship ID rId14 was not found in the file. Web Development Training PHP Básico Definição Preparação de ambiente Sintaxe / Operações básicas 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 1

Upload: mozdevz

Post on 12-Feb-2017

46 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Web Development Training

PHP Básico Definição Preparação de ambiente Sintaxe / Operações básicas

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 1

Page 2: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

O que é PHP ? •  linguagem interpretada •  Interpretado do Servidor • HTML+CSS+JavaScript+PHP

• arquivos PHP tem extensão " .php "

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 2

Page 3: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Seu Poder

• PHP pode gerar páginas com conteúdo dinâmico

• PHP pode criar, abrir, ler, escrever, apagar e fechar arquivos no servidor

• PHP pode coletar dados de formulários

• PHP pode enviar e receber cookies

• PHP pode adicionar, eliminar, modificar dados na base de dados

• PHP pode ser usado para controlar o acesso de utilizadores

• PHP pode criptografar os dados

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 3

Page 4: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Instalação

• Encontrar um host com PHP e suporte ao MySQL •  Instalar um servidor web no seu próprio PC, em seguida,

instalar o PHP e MySQL

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 4

Page 5: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Declaração

<?php //O código PHP fica aqui! ?>

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 5

Page 6: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Variaveis

<?php $txt = "Hello world!"; $x = 5; $y = 10.5;

?>

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 6

Page 7: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Comentários

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0

# Isto é apenas um comentário// Isto também é um comentário/* comentário */

7

Page 8: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

ECHO

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0

<?php $txt1 = "Learn PHP"; $txt2 = "W3Schools.com"; $x = 5; $y = 4; echo "<h2>$txt1</h2>"; echo "Study PHP at $txt2<br>"; echo $x + $y; ?>

8

Page 9: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

If – Then - Else if (condição) { Código que é executado se a condição fôr verdadeira; }

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0

$x = 2; # Variáveisif ($x >= 1 && $x < 3) { // se a variavel $x for maior ou igual a 1 E(AND) menor que 3 echo 'Olá mundo!'; // escreve "Olá mundo!"} else { // Se não... print('Adeus mundo!'); // escreve 'Adeus mundo!', print e echo podem ser usados com ou sem parênteses.}

9

Page 10: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Web Development Training

Formulários e PHP

Ruben Manhiça Jorge Lobo Hervé Muneza

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 10

Page 11: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Conceptos por aprender

• Formulários • Métodos GET e POST

• Acesso no Servidor

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0

The image part with relationship ID rId2 was not found in the file.

11

Page 12: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Formulários

• Permite enviar dados para o servidor

• Pode ser enviado usando os métodos POST e GET

<html> <body> <form action =”processar.php” method=”post"> Name: <input type=”text” name=”nome” /> Age: <input type=”text” name=idade” /> <input type=”submit” /> </form> </body> </html>

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 12

Page 13: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

GET e POST

Criam um vetor com um par de chaves/valores.

Chaves – nomes de controle do formulário;

v a l o r e s – d a d o s introduzidos no formulários .

html> <body> <form action =”processar.php” method=”get"> Name: <input type=”text” name=”nome” /> ....

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 13

Page 14: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

GET

Tem a limitação de só enviar 100 caracteres;

Mostra a informação enviada no Navegador;

Permite guardar a requisição ao Servidor no Bookmarks;

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0

The image part with relationship ID rId2 was not found in the file.

14

Page 15: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

POST

Método POST Não tem limite de tamanho da mensagem a enviar; A informação enviada não é visível no navegador;

html> <body> <form action =”processar.php” method=”post"> Name: <input type=”text” name=”nome” /> ....

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 15

Page 16: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Acesso do Servidor

Método GET

$_GET[”nome"]

Método POST

$_POST[”nome"]

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 16

Page 17: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Exemplo

Index.php html> <body> <form action =”processar.php” method=”post"> Name: <input type=”text” name=”nome” /> Age: <input type=”text” name=idade” /> <input type=”submit” /> </form> </body> </html>

Processar.php <?php If(empty($_POST["nome"])) {

echo ”Preencha o seu nome”; } else { $nome = $_POST["nome"]; }

?>

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 17

Page 18: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Referencias

• Lengstorf, Jason. PHP For Absolute Beginners. [New York.]: Apress, 2009. Print.

• Welling, Luke, and Laura Thomson. PHP And Mysql Web Development. Upper Saddle River, NJ: Addison-Wesley, 2008. Print.

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 18

Page 19: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Web Development Training

PHP e MySQL Ruben Manhiça Jorge Lobo Hervé Muneza

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 19

Page 20: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Base de dados – MySQL – Acesso ao servidor

•  Passo 1 - Abrir conexão com o banco.

•  Antes de criarmos a conexão com o banco devemos ter em mãos algumas informações. São elas:

•  Utilizador – Nome de Utilizador com acesso a base de dados.

•  Senha – Senha do Utilizador.

•  Host – Nome ou IP do servidor. Ex: “localhost”

•  De posse dessas informações podemos criar nossa conexão com a Base de dados utilizando o comando mysql_connect();

mysql_connect(host, Utilizador, senha);

•  Em caso de sucesso, este comando retorna um identificador de conexão. Em caso de falha este comando retornará FALSE.

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 20

Page 21: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Base de dados – MySQL – Acesso ao servidor

• Exemplo $conexao = mysql_connect(“host”,“Utilizador”, “senha”); if ($conexao == TRUE){

echo “Conexão com o servidor efetuada com sucesso.”; }else{

echo “Falha ao conectar no servidor.”; }

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 21

Page 22: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Base de dados – MySQL – Acesso ao servidor

• Passo 3 – Fechar conexão com o Base de dados. •  Após a execução dos comandos no banco devemos fechar a conexão

com o servidor para poupar recursos do servidor.

•  Para fechar a conexão com o banco utilizamos a função mysql_close().

mysql_close(identificador de conexão);

•  O comando mysql_close() retorna TRUE em caso de sucesso e FALSE em caso de falha;

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 22

Page 23: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Base de dados – MySQL – Acesso ao servidor

• Exemplo $conexao = mysql_connect(“host”,“Utilizador”, “senha”); if ($conexao == TRUE){

echo “Conexão com o servidor efetuada com sucesso.”; }else{

echo “Falha ao conectar no servidor.”; } if(mysql_close($conexao)){

echo “Conexão com o banco fechada com sucesso.”; }else{

echo “Não havia conexão aberta ou a conexão já tinha sido fechada.”; }

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 23

Page 24: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Base de dados – MySQL – Manipulação de Dados

• Passo 2 – Executar comandos na Base de dados. •  Após conectar no servidor de Base de dados, devemos especificar

qual base de dados será utilizada. Isto é feito através da função mysql_select_db();

mysql_select_db(nome do banco);

•  A execução de comandos no MySQL é feita através de declarações SQL.

•  Após a definição do comando, podemos executar o comando no banco através do método mysql_query();

mysql_query(declaração_sql);

•  Além disso, ao executar o comando, esta função faz com que a variável que estiver representando-a, armazene informações a respeito da instrução SQL executada. $variavel = mysql_query(declaração_sql);

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 24

Page 25: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Base de dados – MySQL – Manipulação de Dados

•  O tipo de informações armazenadas dependerão do tipo de instrução

SQL executada.

•  Para outros tipos de consultas SQL, INSERT, UPDATE, DELETE, DROP,

etc, mysql_query() retorna TRUE em caso de sucesso ou FALSE em

caso de erro.

•  Para comandos SELECT, SHOW, DESCRIBE ou EXPLAIN,

mysql_query() retorna um resource em caso de sucesso, ou FALSE em

caso de falha.

•  Neste último caso, os resultados da instrução SQL podem ser acessadas

através de outras funções da biblioteca mysql.

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 25

Page 26: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Base de dados – MySQL – Manipulação de Dados

•  O recurso de resultado retornado pode ser passado para

mysql_fetch_array(), e outras funções para manipular tabelas de

resultados, para acessar os dados retornados.

•  Use mysql_num_rows(query) para obter quantas linhas foram retornadas

para um comando SELECT ou mysql_affected_rows(link resource) para

obter quantas linhas foram afetadas por um comando DELETE, INSERT,

REPLACE, ou UPDATE.

•  mysql_query() irá também falhar e retornar FALSE se o Utilizador não

tiver permissões para acessar a tabela(s) referenciadas pela consulta.

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 26

Page 27: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Base de dados – MySQL – Manipulação de Dados

•  Exemplo do uso de comando INSERT:

$conexao = mysql_connect(“host”,“Utilizador”, “senha”); $banco = mysql_select_db(“banco”);

$sql = “INSERT INTO FUNCIONARIO (MATRICULA, NOME) VALUES (1,’FULANO’)”; $resultado = mysql_query($sql, $conexao); if ($resultado){

$numeroRegistros = mysql_affected_rows($conexao); echo “Comando executado com sucesso. ”; echo “Foram afetados $numeroRegistros registros.”;

}else{ echo “Falha ao executar comando.”;

} mysql_close($conexao);

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 27

Page 28: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Base de dados – MySQL – Manipulação de Dados

•  No caso de comandos que retornam informações da BD, podemos utilizar algumas funções para extrair as informações armazenadas no recurso de resultado. São elas:

•  mysql_fetch_row – recupera o próximo registro em forma de array de índices numéricos.

•  mysql_fetch_assoc – recupera o próximo registro em forma de array de índices associativos, onde cada índice é o nome do campo na tabela.

•  mysql_fecth_array – recupera o próximo registro em forma de array de índices numéricos e associativos, ao mesmo tempo.

•  mysql_fecth_object - recupera o próximo registro em forma de objeto.

•  Todas elas necessitam como parâmetro do recurso contendo o resultado do comando mysql_query()

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 28

Page 29: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Base de dados – MySQL – Manipulação de Dados

•  Exemplo do uso de comando SELECT: $conexao = mysql_connect(“Utilizador”, “senha”, “host”); $banco = mysql_select_db(“banco”);

$sql = “SELECT matricula, nome, salario FROM funcionario”; $resultado = mysql_query($sql, $conexao,); if ($resultado){

while ($registro = mysql_fecth_array($resultado)){ echo “Matricula: ”.$registro[”matricula”]; echo “Nome: ”. $registro[”nome”]; echo “Salário: ”. $registro[”salario”]; }

} mysql_close($conexao);

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 29

Page 30: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Herança

• Permite reutilizar uma classe ou expandir para diferente proposito.

• A classe filho herda os métodos e propriedades da classe pai.

• Construtores ???

<?php

Class cao extends mamifero {

... }

?>

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 30

Page 31: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Web Development Training

MVC Model – View - Controller Definição Model Controller View Vantagem

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 31

Page 32: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

O que é MVC?

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0

"MVC é um padrão de arquitetura que descreve uma forma de estruturar nossa aplicação e as responsabilidades e interações para cada parte nessa estrutura."

32

Page 33: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

MVC

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 33

Page 34: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Model (Modelo)

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0

O modelo é o de dados e as regras aplicáveis a esses dados, que representam conceitos geridos por uma aplicação

34

Page 35: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Controller (Controlador)

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0

O controlador gere as solicitações do utilizador (recebidos como HTTP GET ou POST solicitados quando o utilizador clica em elementos GUI para executar ações)

Sua principal função é chamar e coordenar os recursos necessários / objetos necessários para executar a ação do utilizador

35

Page 36: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Exemplo - Controller (Controlador)

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0

<?php   class BooksController extends AppController {    function list($category) {    $this->set('books', $this->Book->findAllByCategory($category));    }    function add() { ... ... }    function delete() { ... ... }    ... ... } ?>

36

Page 37: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

View

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0

View oferece maneiras diferentes de apresentar os dados recebidos a partir do modelo.

<table> <tr> <th>Title</th> <th>Author</th> <th>Price</th> </tr>   <?php foreach ($books as $book): ?> <tr> <td> <?php echo $book['Book']['title']; ?> </td> <td> <?php echo $book['Book']['author']; ?> </td> <td> <?php echo $book['Book']['price']; ?> </td> </tr> <?php endforeach; ?>   </table>

37

Page 38: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

MVC

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 38

Page 39: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Vantagem

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0

"A vantagem mais óbvia que ganhamos usando MVC é uma clara separação de apresentação (a interface com o utilizador) e lógica

da aplicação.”

39

Page 40: Web Training Aula 02: Introduction to PHP

The image part with relationship ID rId14 was not found in the file.

The image part with relationship ID rId14 was not found in the file.

Para proxima semana

• Dar vida aos formularios…

3/28/16 Presenta/onlicencedundernon-commercialcrea/vecommons3.0 40