SlideShare a Scribd company logo
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
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.
O que é PHP ?
•  linguagem interpretada
•  Interpretado do Servidor
•  HTML+CSS+JavaScript+PHP
•  arquivos PHP tem extensão
" .php "
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
2
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
3
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
4
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.
Declaração
<?php
//O código PHP fica aqui!
?>
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
5
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.
Variaveis
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
6
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.
Comentários
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
# Isto é apenas um comentário
// Isto também é um comentário
/* comentário */
7
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.
ECHO
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.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
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.
If – Then - Else
if (condição) {
Código que é executado se a condição fôr
verdadeira;
}
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
$x = 2; # Variáveis
if ($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
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
Formulários e PHP
Ruben Manhiça
Jorge Lobo
Hervé Muneza
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
10
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.
Conceptos por aprender
• Formulários
• Métodos GET e POST
• Acesso no Servidor
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
The image part with relationship ID rId2 was not found in the file.
11
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
12
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
13
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
The image part with relationship ID rId2 was not found in the file.
14
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
15
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.
Acesso do Servidor
Método GET
$_GET[”nome"]
Método POST
$_POST[”nome"]
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
16
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
17
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
18
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 e MySQL
Ruben Manhiça
Jorge Lobo
Hervé Muneza
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
19
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
20
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
21
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
22
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
23
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
24
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
25
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
26
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
27
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
28
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
29
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.
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/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
30
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
MVC
Model – View - Controller
Definição
Model
Controller
View
Vantagem
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
31
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.
O que é MVC?
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.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
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.
MVC
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
33
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.
Model (Modelo)
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
O modelo é o de dados e as regras aplicáveis a
esses dados, que representam conceitos geridos
por uma aplicação
34
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.
Controller (Controlador)
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.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
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.
Exemplo - Controller (Controlador)
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
<?php
 
class BooksController extends AppController {
 
 function list($category) {
 
 $this->set('books', $this->Book-
>findAllByCategory($category));
 
 }
 
 function add() { ... ... }
 
 function delete() { ... ... }
 
 ... ... } ?>	
36
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.
View
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.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
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.
MVC
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
38
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.
Vantagem
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.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
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.
Para proxima semana
•  Dar vida aos formularios…
3/28/16	
Presenta/on	licenced	under	non-commercial	crea/ve	
commons	3.0	
40

More Related Content

Viewers also liked

Biology paper 02 jan 2009
Biology paper 02 jan 2009Biology paper 02 jan 2009
Biology paper 02 jan 2009Bruce19
 
Nord pas de calais picardie
Nord pas de calais picardieNord pas de calais picardie
Nord pas de calais picardie
TRANCHONT
 
Misty Russo - Resume
Misty Russo - ResumeMisty Russo - Resume
Misty Russo - ResumeMisty Russo
 
Acidente nuclear de chernobil 2 E
Acidente nuclear de chernobil  2 EAcidente nuclear de chernobil  2 E
Acidente nuclear de chernobil 2 E
Maria Teresa Iannaco Grego
 
Conferencia de-berlín
Conferencia de-berlínConferencia de-berlín
Conferencia de-berlín
victoriamn2013
 

Viewers also liked (6)

Netvibes - Mode d'emploi
Netvibes - Mode d'emploiNetvibes - Mode d'emploi
Netvibes - Mode d'emploi
 
Biology paper 02 jan 2009
Biology paper 02 jan 2009Biology paper 02 jan 2009
Biology paper 02 jan 2009
 
Nord pas de calais picardie
Nord pas de calais picardieNord pas de calais picardie
Nord pas de calais picardie
 
Misty Russo - Resume
Misty Russo - ResumeMisty Russo - Resume
Misty Russo - Resume
 
Acidente nuclear de chernobil 2 E
Acidente nuclear de chernobil  2 EAcidente nuclear de chernobil  2 E
Acidente nuclear de chernobil 2 E
 
Conferencia de-berlín
Conferencia de-berlínConferencia de-berlín
Conferencia de-berlín
 

Similar to Web Training Aula 02: Introduction to PHP

Intro to Php Security
Intro to Php SecurityIntro to Php Security
Intro to Php Security
Dave Ross
 
PHP SA 2014 - Releasing Your Open Source Project
PHP SA 2014 - Releasing Your Open Source ProjectPHP SA 2014 - Releasing Your Open Source Project
PHP SA 2014 - Releasing Your Open Source Project
xsist10
 
working with PHP & DB's
working with PHP & DB'sworking with PHP & DB's
working with PHP & DB's
Hi-Tech College
 
Developing on the aloashbei platform
Developing on the aloashbei platformDeveloping on the aloashbei platform
Developing on the aloashbei platform
pycharmer
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
sekar c
 
P H P Part I I, By Kian
P H P  Part  I I,  By  KianP H P  Part  I I,  By  Kian
P H P Part I I, By Kianphelios
 
Old WP REST API, New Tricks
Old WP REST API, New TricksOld WP REST API, New Tricks
Old WP REST API, New Tricks
WordPress Community Montreal
 
API-first development
API-first developmentAPI-first development
API-first development
Vasco Veloso
 
How to learn to build your own PHP framework
How to learn to build your own PHP frameworkHow to learn to build your own PHP framework
How to learn to build your own PHP framework
Dinh Pham
 
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkHanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkNguyen Duc Phu
 
Building Web Hack Interfaces
Building Web Hack InterfacesBuilding Web Hack Interfaces
Building Web Hack Interfaces
Christian Heilmann
 
Boston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsBoston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on Rails
John Brunswick
 
MYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptx
MYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptxMYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptx
MYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptx
ArjayBalberan1
 
CICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your MindCICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your Mindciconf
 
A RESTful introduction
A RESTful introductionA RESTful introduction
A RESTful introduction
Daniel Toader
 
FamilySearch Reference Client
FamilySearch Reference ClientFamilySearch Reference Client
FamilySearch Reference Client
Dallan Quass
 

Similar to Web Training Aula 02: Introduction to PHP (20)

Intro to Php Security
Intro to Php SecurityIntro to Php Security
Intro to Php Security
 
PHP SA 2014 - Releasing Your Open Source Project
PHP SA 2014 - Releasing Your Open Source ProjectPHP SA 2014 - Releasing Your Open Source Project
PHP SA 2014 - Releasing Your Open Source Project
 
working with PHP & DB's
working with PHP & DB'sworking with PHP & DB's
working with PHP & DB's
 
Developing on the aloashbei platform
Developing on the aloashbei platformDeveloping on the aloashbei platform
Developing on the aloashbei platform
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
 
P H P Part I I, By Kian
P H P  Part  I I,  By  KianP H P  Part  I I,  By  Kian
P H P Part I I, By Kian
 
Cqrs api v2
Cqrs api v2Cqrs api v2
Cqrs api v2
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Old WP REST API, New Tricks
Old WP REST API, New TricksOld WP REST API, New Tricks
Old WP REST API, New Tricks
 
API-first development
API-first developmentAPI-first development
API-first development
 
How to learn to build your own PHP framework
How to learn to build your own PHP frameworkHow to learn to build your own PHP framework
How to learn to build your own PHP framework
 
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkHanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
 
Phphacku iitd
Phphacku iitdPhphacku iitd
Phphacku iitd
 
Building Web Hack Interfaces
Building Web Hack InterfacesBuilding Web Hack Interfaces
Building Web Hack Interfaces
 
Boston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on RailsBoston Computing Review - Ruby on Rails
Boston Computing Review - Ruby on Rails
 
MYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptx
MYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptxMYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptx
MYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptx
 
CICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your MindCICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your Mind
 
A RESTful introduction
A RESTful introductionA RESTful introduction
A RESTful introduction
 
Resume
ResumeResume
Resume
 
FamilySearch Reference Client
FamilySearch Reference ClientFamilySearch Reference Client
FamilySearch Reference Client
 

Recently uploaded

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 

Recently uploaded (20)

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 

Web Training Aula 02: Introduction to PHP

  • 1. 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
  • 2. 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. O que é PHP ? •  linguagem interpretada •  Interpretado do Servidor •  HTML+CSS+JavaScript+PHP •  arquivos PHP tem extensão " .php " 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 2
  • 3. 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. 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/on licenced under non-commercial crea/ve commons 3.0 3
  • 4. 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. 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/on licenced under non-commercial crea/ve commons 3.0 4
  • 5. 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. Declaração <?php //O código PHP fica aqui! ?> 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 5
  • 6. 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. Variaveis <?php $txt = "Hello world!"; $x = 5; $y = 10.5; ?> 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 6
  • 7. 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. Comentários 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 # Isto é apenas um comentário // Isto também é um comentário /* comentário */ 7
  • 8. 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. ECHO 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.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
  • 9. 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. If – Then - Else if (condição) { Código que é executado se a condição fôr verdadeira; } 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 $x = 2; # Variáveis if ($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
  • 10. 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 Formulários e PHP Ruben Manhiça Jorge Lobo Hervé Muneza 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 10
  • 11. 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. Conceptos por aprender • Formulários • Métodos GET e POST • Acesso no Servidor 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 The image part with relationship ID rId2 was not found in the file. 11
  • 12. 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. 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/on licenced under non-commercial crea/ve commons 3.0 12
  • 13. 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. 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/on licenced under non-commercial crea/ve commons 3.0 13
  • 14. 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. 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/on licenced under non-commercial crea/ve commons 3.0 The image part with relationship ID rId2 was not found in the file. 14
  • 15. 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. 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/on licenced under non-commercial crea/ve commons 3.0 15
  • 16. 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. Acesso do Servidor Método GET $_GET[”nome"] Método POST $_POST[”nome"] 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 16
  • 17. 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. 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/on licenced under non-commercial crea/ve commons 3.0 17
  • 18. 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. 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/on licenced under non-commercial crea/ve commons 3.0 18
  • 19. 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 e MySQL Ruben Manhiça Jorge Lobo Hervé Muneza 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 19
  • 20. 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. 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/on licenced under non-commercial crea/ve commons 3.0 20
  • 21. 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. 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/on licenced under non-commercial crea/ve commons 3.0 21
  • 22. 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. 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/on licenced under non-commercial crea/ve commons 3.0 22
  • 23. 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. 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/on licenced under non-commercial crea/ve commons 3.0 23
  • 24. 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. 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/on licenced under non-commercial crea/ve commons 3.0 24
  • 25. 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. 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/on licenced under non-commercial crea/ve commons 3.0 25
  • 26. 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. 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/on licenced under non-commercial crea/ve commons 3.0 26
  • 27. 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. 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/on licenced under non-commercial crea/ve commons 3.0 27
  • 28. 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. 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/on licenced under non-commercial crea/ve commons 3.0 28
  • 29. 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. 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/on licenced under non-commercial crea/ve commons 3.0 29
  • 30. 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. 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/on licenced under non-commercial crea/ve commons 3.0 30
  • 31. 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 MVC Model – View - Controller Definição Model Controller View Vantagem 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 31
  • 32. 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. O que é MVC? 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.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
  • 33. 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. MVC 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 33
  • 34. 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. Model (Modelo) 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 O modelo é o de dados e as regras aplicáveis a esses dados, que representam conceitos geridos por uma aplicação 34
  • 35. 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. Controller (Controlador) 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.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
  • 36. 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. Exemplo - Controller (Controlador) 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 <?php   class BooksController extends AppController {    function list($category) {    $this->set('books', $this->Book- >findAllByCategory($category));    }    function add() { ... ... }    function delete() { ... ... }    ... ... } ?> 36
  • 37. 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. View 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.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
  • 38. 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. MVC 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 38
  • 39. 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. Vantagem 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.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
  • 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. Para proxima semana •  Dar vida aos formularios… 3/28/16 Presenta/on licenced under non-commercial crea/ve commons 3.0 40