Documente Academic
Documente Profesional
Documente Cultură
1
APOSTILA DE PHP
2
APOSTILA DE PHP
Apostila de
PHP
3
APOSTILA DE PHP
Aparecido Quesada
Adriana Tosta
Eder Moura Dourado
Simone Leal dos Santos
Thyago Akira de Morais Ribeiro
Yuri Robinson de Souza
Contato
treinamento_cge@prefeitura.sp.gov.br
telecentros@prefeitura.sp.gov.br
PALCIO DO ANHANGABA
VIADUTO DO CH N 15
CEP 01002-000 SO PAULO
TEL: 3113-8938 FAX 3113-8939
4
APOSTILA DE PHP
ndice
5
APOSTILA DE PHP
6
APOSTILA DE PHP
7
APOSTILA DE PHP
8
APOSTILA DE PHP
O que PHP?
Histria
9
APOSTILA DE PHP
Vantagens
10
APOSTILA DE PHP
Visualizao:
Configurao
PC 386 ou superior
16 MB de memria RAM
100 MB livres em disco (PHP + MySQL + Apache)
11
APOSTILA DE PHP
Software:
Instalao do MySQL
12
APOSTILA DE PHP
#cd /usr/src
13
APOSTILA DE PHP
14
APOSTILA DE PHP
Teste de Funcionamento
Ex:
http://localhost/pastahabilitada/teste.php.
<?php
phpinfo();
?>
15
APOSTILA DE PHP
16
APOSTILA DE PHP
<html>
<head>
<title>Script PHP</title>
</head>
<body>
<?php
echo Ol, eu sou um script PHP!!!;
?>
</body>
</html>
COMENTRIOS
17
APOSTILA DE PHP
<?
echo teste; /* Isto um comentrio com mais
de uma linha, mas no funciona corretamente ?>
*/
<?
echo teste; /* Isto um comentrio com mais
de uma linha que funciona corretamente
*/
?>
EXERCICOS
18
APOSTILA DE PHP
<html>
<title>Exercicio 1</title>
<body>
A primeira linha e <u>normal</u>. <br>
<br>
Nisto, vem uma <font color=#FF0000>terceira mais
complexa</font>... <br>
</body>
</html>
Variveis
19
APOSTILA DE PHP
INTEGER (INTEIRO)
STRINGS
20
APOSTILA DE PHP
<?
$curso1 = 20;
$curso2 = curso1 igual a $curso1';
echo $curso2;
// Ficar: $curso2 = curso1 igual a 20'
?>
<?
$curso1 = 20;
$curso2 = curso1 no igual a $curso1;
echo $curso2;
// Ficar: $curso2 = curso1 no igual a $curso1'
?>
BOOLEANO
ARRAY
OBJETO
21
APOSTILA DE PHP
Caracteres de Escape
EXERCCIOS:
22
APOSTILA DE PHP
<html>
<title>Exercicio 2</title>
<body>
<?
$inteiro=10;
$real=20.0;
$caracter= V;
$cor1= #FF0000;
$cor2= #0000FF;
?>
</body>
</html>
23
APOSTILA DE PHP
Operadores
ARITMTICOS
OPERADOR SIGNIFICADO
+ Adio
- Subtrao
* Multiplicao
/ Diviso
% Resto de diviso
STRING
<?
$x = Al ;
$s = $x.Mundo;
echo($s.\n); // Imprimir Al Mundo
?>
24
APOSTILA DE PHP
ATRIBUIO
OPERADOR SIGNIFICADO
= Atribuio simples.
<?
$curso = 7;
$curso += 2; //($curso fica com o valor 9)
echo $curso;
?>
25
APOSTILA DE PHP
<?
$resto = 11;
$resto %= 2; //($resto fica com o valor 1)
echo $resto;
?>
++ incremento
decremento
Exemplos:
LGICOS
26
APOSTILA DE PHP
or ou lgico $a or $b
! No (inverso) !$b
|| ou lgico $a || $b
COMPARAO
== igual a
!= diferente de
<> Diferente de
27
APOSTILA DE PHP
Estruturas de Controle
$a = 1;
if ($a == 1)
{
...
...
...
}
<?
$a = 1;
$b = 2;
if ($a > $b)
{
echo $a > $b;
}
else
{
echo $b > $a;
}
?>
28
APOSTILA DE PHP
<?
$a = 1;
$b = 2;
$c = 3;
if ($a > $b)
{
echo $a e´ maior que $b;
}
elseif ($a > $c)
{
echo $a e´ maior que $c;
}
else
{
echo $a e´ menor que $b e $c;
}
?>
29
APOSTILA DE PHP
if ($i == 0)
print i igual a zero;
elseif ($i == 1)
print i igual a um;
elseif ($i == 2)
print i igual a dois;
}
switch ($i) {
case 0:
print i igual a zero;
break;
case 1:
print i igual a um;
break;
case 2:
print i igual a dois;
break;
}
(expressao1)?(expressao2):( expressao3)
30
APOSTILA DE PHP
<?
echo While.<br>;
$a = 1;
while ($a <= 10)
{
echo Número: .$a++.<br>;
}
?>
<?
echo Do...While.<br>;
$c = 0;
do
{
echo Número: .++$c. <br>;
} while ($c < 10);
?>
31
APOSTILA DE PHP
<?
echo For...Next.<br>;
for ($a=0; $a<=10; $a++)
{
echo Número: .$a.<br>;
}
?>
EXERCICOS:
<html>
<title>verifica.php</title>
<body>
<?
//Condicao de texto em italico
if ($italico== on)
{
$italico_abre= <i>;
$italico_fecha= </i>;
}
else
{
$italico_abre= ;
$italico_fecha= ;
}
32
APOSTILA DE PHP
33
APOSTILA DE PHP
Quebra de Fluxo
<?
$a = 20;
while ($a > 0)
{
if ($a == 5)
{
echo Número inválido!;
break;
}
echo Número .$a.<br>;
$a;
}
?>
<?
for ($a=0;$a<10;$a++)
{
if ($a == 5)
{
continue;
}
else
{
echo Nmero: .$a.<br>;
}
}
?>
34
APOSTILA DE PHP
Include
Programa: Teste.php
<?
echo Teste A;
echo Teste B;
include Externo.php;
echo Teste D;
?>
Programa: Externo.php
<?
echo Teste C;
?>
<?
echo Teste A;
echo Teste B;
echo Teste C;
echo Teste D;
?>
35
APOSTILA DE PHP
Funes
Onde:
soma o nome da funo.
$a e $b so argumentos.
$c o valor retornado.
36
APOSTILA DE PHP
<?
$a=12;
$b=14;
echo Exemplo de uso de funes em PHP;
soma($a,$b);
function soma($a, $b)
{
$c = $a + $b;
return $c;
}
echo <br>$a<br>$b;
?>
<?
echo Exemplo de uso de funes em PHP;
$nome=FulAno DOs Santos;
$nome=strtolower($nome);
echo $nome;
?>
37
APOSTILA DE PHP
Passagem de Argumentos
function arg_ref(&$varivel)
{
$varivel = valor;
}
function mais5($numero) {
$numero += 5;
}
$a = 3;
mais5($a); //$a continua valendo 3
38
APOSTILA DE PHP
39
APOSTILA DE PHP
40
APOSTILA DE PHP
VARIVEIS GLOBAIS
Exemplo:
$curso = PHP
function mostra()
{
global $curso;
echo $curso;
}
mostra();
VARIVEIS LOCAIS
Exemplo:
function mostra()
{
$x = 15;
echo $x;
}
echo $x; //No imprimir nada j que $x no global
mostra(); //Imprimir 15
41
APOSTILA DE PHP
VARIVEIS ESTTICAS
function incrementa()
{
static $x = 0;
echo $x;
$x++;
}
EXERCICOS:
<html>
<title>Exercicio</title>
<body>
<?
// calcula a soma de duas variaveis
function soma($a,$b)
{
42
APOSTILA DE PHP
$total=$a+$b;
return ($total);
}
//calcula a subtracao de duas variaveis
function subtracao($a,$b)
{
$total=$a-$b;
return ($total);
}
//calcula a multiplicacao de duas variaveis
function multiplicacao($a,$b)
{
$total=$a*$b;
return ($total);
}
//calcula a divisao de duas variaveis
function divisao($a,$b)
{
$total=$a/$b;
return ($total);
}
43
APOSTILA DE PHP
$div=divisao($a,$b);
echo A diviso de $a por $b $div !<br>;
?>
</body>
</html>
Arrays
<?
$array[0] = Curso;
$array[1] = PHP;
$array[MPB] = Gilberto Gil;
echo $array[0].<br>;
echo $array[1].<br>;
echo $array[MPB].<br>;
?>
Listas
<?
list($a, $b, $c) = array(0 => a, 1 => b, 2 => c);
?>
44
APOSTILA DE PHP
EXERCICOS:
<html>
<title>Exercicio</title>
<body>
<?
$meses=array( Janeiro, Fevereiro, Maro, Abril,
Maio, Junho, Julho, Agosto, Setembro, Outubro,
Novembro, Dezembro);
?>
Ciclo While
<br><br>
<?
$mes=0;
while ($mes<=11)
{
echo Ms: $meses[$mes] <br>;
$mes++ ;
}
?>
<br><br><br>
Ciclo For
<br><br>
<?
45
APOSTILA DE PHP
46
APOSTILA DE PHP
REALIZANDO CONSULTAS
47
APOSTILA DE PHP
APAGANDO O RESULTADO
NMERO DE LINHAS
UTILIZANDO OS RESULTADOS
48
APOSTILA DE PHP
Projeto
Roteiro:
49
APOSTILA DE PHP
Tipos de Campos
50
APOSTILA DE PHP
Dicas:
OPERAO COMANDO
51
APOSTILA DE PHP
Roteiro:
52
APOSTILA DE PHP
3 - MDULO DE INCLUSO
53
APOSTILA DE PHP
Dica:
Quando o servidor recebe a requisio de uma pgina HTML,
ele apenas envia a pgina requisitada. Por outro lado, quando a
requisio de uma pgina com extenso PHP, o servidor processa
o cdigo antes de envi-la. Pode-se combinar os cdigos HTML e
PHP.
54
APOSTILA DE PHP
Dicas:
No cdigo referente ao programa incluso.php, voc utilizar
algumas funes do PHP:
<html>
<head>
<title>Inclusao.php</title>
</head>
<body bgcolor=#FFFFFF>
<?php
// Consiste Nome
if (empty($nome) || empty($telefone) || empty($cargo))
{
55
APOSTILA DE PHP
56
APOSTILA DE PHP
</form>
</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
);
}
else {
// Declarao SQL
$declar = INSERT into alunos values ($nome,
$cargo,
$telefone, $email);
// Roda a query e trata o resultado
57
APOSTILA DE PHP
}
else {
echo (<BR><BR>);
echo (<center> <b> <font size = 4> Erro - Inclusã
o não Efetuada
</font>
</b> </center>);
echo (<BR>);
echo (<center> <b> <a href=\inclusao.html\>
Voltar</a> </b>
</center>);
}
Roteiro:
58
APOSTILA DE PHP
8.Insira 3 funcionrios.
4 - MDULO DE CONSULTA
<html>
<head> <title>Consulta.html</title>
</head>
<body bgcolor=#FFFFFF>
<table width=640" border=0" cellspacing=0" align=
center>
<tr valign=top>
<td>
<p><img src=telecentro.gif width=640"
height=44"></p>
59
APOSTILA DE PHP
<!mensagem>
<p><b>Formulário de Consulta<br>
</b></p>
<form method=post action=consulta.php>
<p>Nome completo:
<input type=text name=nome size=25"
maxlength=50">
</p>
<p>
<input type=submit name=Submit value=
Enviar> </p>
</form>
<center> <b> <a href=index.html>Home</a> </b>
</center>
</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</body>
</html>
60
APOSTILA DE PHP
Dicas:
61
APOSTILA DE PHP
<html>
<head>
<title>Consulta.php</title>
</head>
<body bgcolor=#FFFFFF>
<?php
// Tira os espaos em branco das variveis recebidas pelo
formulrio
$nome = trim($nome);
// Consiste Nome
if (empty($nome)) {
$html = file(consulta.html);
$html = implode( ,$html);
$erro = <center><font color=\#FF0000\> Preencha o
campo<b>Nome</b></font></center>;
$html = str_replace(<!mensagem>,$erro,$html);
echo ($html);
}
else {
echo (<p><center><img src=\telecentro.gif\ width=\640\
height=\44\></center></p>);
// Declarao do SQL
$declar = SELECT cargo, telefone, email from alunos
where nome = $nome;
// Roda a query e verifica se encontrou registro
$query = mysql_db_query (telecentros, $declar, $conec)
or die (Erro no
acesso ao banco);
$achou = mysql_num_rows($query);
62
APOSTILA DE PHP
// echo ($achou);
// Se encontrou, guarda as variveis
if ($achou > 0) {
$row = mysql_fetch_row ($query);
$cargo = $row[0];
$telefone = $row[1];
$email = $row[2];
echo (<BR>);
echo (<table width=\640\ border=\0\ cellspacing=\0\
align=\center\> <tr> <td>);
echo (<b> Resultado da Consulta </b>);
echo (<BR><BR>);
echo (<b> Nome: </b> $nome <BR>);
echo (<b> Cargo: </b> $cargo <BR>);
echo (<b> Telefone: </b> $telefone <BR>);
echo (<b> E-mail: </b> $email <BR>);
echo (</td> </tr> </table>);
echo (<center> <b> <a href=\consulta.html\>Voltar</
a> </b>
</center>);
}
else {
echo (<BR>);
echo (<center> <b> Aluno não cadastrado
</b> </center>);
echo (<BR>);
echo (<center> <b> <a href=\consulta.html\>Voltar</
a> </b>
</center>);
}
}
?>
</body>
</html>
63
APOSTILA DE PHP
Roteiro:
64
APOSTILA DE PHP
5 - MDULO DE EXCLUSO
<html>
<head>
<title>Exclusao.html</title>
<meta http-equiv=Content-Type content=text/
html; charset=iso-8859-1">
</head>
<body bgcolor=#FFFFFF>
<table width=640" border=0" cellspacing=0" align=
center>
<tr valign=top>
<td>
<p><img src=telecentro.gif width=
640" height=44"></p>
<!mensagem>
<p><b>Formulário de Exclusão: <br>
</b></p>
<form method=post action=exclusao.php>
<p>Nome Completo:
<input type=text name=nome size=
25" maxlength=50">
</p>
<p>
<input type=submit name=Submit value=
Enviar>
</p>
</form>
<center> <b> <a href=index.html>Home</a> </b>
</center>
</td>
</tr>
65
APOSTILA DE PHP
<tr>
<td> </td>
</tr>
</table>
</body>
</html>
<html>
<head>
<title>Exclusao.php</title>
</head>
<body bgcolor=#FFFFFF>
<?php
// Consiste Nome
if (empty($nome)) {
$html = file(exclusao.html);
$html = implode( ,$html);
$erro = <center><font color=\#FF0000\> Preencha o
66
APOSTILA DE PHP
campo<b>Nome</b></font></center>;
$html = str_replace(<!mensagem>,$erro,$html);
echo ($html);
}
else {
echo (<p><center><img src=\telecentro.gif\ width=\640\
height=\44\></center></p>);
// Declarao do SQL
$declar = SELECT nome from alunos where nome =
$nome;
echo (<BR><BR>);
echo (<center> Aluno: $nome </center>);
echo (<BR>);
67
APOSTILA DE PHP
echo (<BR><BR>);
echo (<center> <b> <font size = 4>
Excluso Efetuada </font> </b>
</center>);
echo (<BR><BR>);
echo (<center> <b> <a href=\exclusao.html\>Voltar</a>
</b>
</center>);
}
else {
echo (<BR><BR>);
echo (<center> <b> <font size = 4>
Erro - Exclusão não Efetuada
</font>
</b> </center>);
echo (<BR><BR>);
echo (<center> <b> <a href=\exclusao.html\>
Voltar</a> </b>
</center>);
}
}
else {
echo (<BR><BR>);
echo (<center> <b> Aluno não cadastrado
</b>
</center>);
echo (<BR><BR>);
echo (<center> <b> <a href=\exclusao.html\>Voltar
</a> </b>
</center>);
}
mysql_close ($conec);
}
?>
</body>
</html>
68
APOSTILA DE PHP
Roteiro:
6 - MDULO DE ALTERAO
69
APOSTILA DE PHP
<html>
<head>
<title>Alteracao.php</title>
</head>
<body bgcolor=#FFFFFF>
<?php
include (funcoes.php);
// Consiste Nome
if (empty($nome)) {
$html = file(alteracao.html);
$html = implode( ,$html);
$erro = <center><font color=\#FF0000\> Preencha o
campo<b>Nome</b></font></center>;
$html = str_replace(<!mensagem>,$erro,$html);
echo ($html);
}
else {
echo (<p><center><img src=\telecentro.gif\ width=
\640\height=\44\></center></p>);
70
APOSTILA DE PHP
// Declarao do SQL
$declar = SELECT cargo, telefone, email from alunos
where nome = $nome;
71
APOSTILA DE PHP
</body>
</html>
72
APOSTILA DE PHP
<?php
function
monta_pagina($nome,$cargo,$telefone,$email)
{
echo <table width=\640\ border=\0\ cellspacing=\0\
align=\center\>;
echo <tr>;
echo <td>;
echo <p><b>Formulário de Alteraçã
o: <br></b></p>;
echo <form method=\post\ action=\alteracao2.php\>;
echo <p>Nome: $nome </p>;
echo <p>Cargo: <input type=\text\ name=\cargo
\ value=\$cargo\
size=\40\ maxlength=\40\> </p>;
echo <p>Telefone: <input type=\text\ name=\telefone\
value=\$telefone\ maxlength=\10\ size=\10\> </p>;
echo <p>E-mail: <input type=\text\ name=\email
\ value=\$email\
size=\25\ maxlength=\25\> </p>;
echo <p> <input type=\submit\ name=\Submit
\ value=\Enviar\>
</p>;
echo <p> <input type=\hidden\ name=\nome
\ value=\$nome\></p>;
echo </form>;
echo </td>;
echo </tr>;
echo <tr>;
echo </tr>;
echo </table>;
echo (<center> <b> <a href=\alteracao.html\>Voltar</a>
</b>
</center>);
return; }
?>
73
APOSTILA DE PHP
<html>
<head>
<title>Alteracao2.php</title>
<meta http-equiv=Content-Type content=text/
html; charset=iso-8859-1">
</head>
<body bgcolor=#FFFFFF>
<p><center><img src=telecentro.gif width=
640" height=44"></center></p>
<?php
include (funcoes.php);
// Tira os espaos em branco das variveis recebidas
pelo formulrio
$nome = trim($nome);
$cargo = trim($cargo);
$telefone = trim($telefone);
$email = trim($email);
74
APOSTILA DE PHP
{
echo (<font color=\#FF0000\>
<b>Campo(s) obrigatório(s) não preenchido(s)
</b></font>);
monta_pagina($nome, $cargo, $telefone, $email);
}
else
{
// Cria uma conexo com o servidor MySQL
$conec = mysql_connect (localhost,root,telecentros)
or die
// consulta SQL pra atualizar a tabela do banco de dados
$declar=UPDATE alunos SET nome=
$nome, cargo=$cargo, email=$email, telefone=
$telefone WHERE nome=$nome;
// Roda a query e trata o resultado
if (mysql_db_query (telecentros, $declar, $conec)) {
echo (<BR><BR>);
echo <center> <b> <font size = 4> Altera&o Efetuada!
</font> </b>
</center>;
echo (<br>);
75
APOSTILA DE PHP
Roteiro:
76
APOSTILA DE PHP
para criar uma pgina simples que agradece ao usurio pelo uso
do sistema, e salve-a com o nome de sair.html.
Dicas:
j: dia
m: ms
Y: ano
H: hora
i: minutos
s: segundos
<html>
<head>
<title>Função Data e Hora</title>
</head>
<body bgcolor=#FFFFFF>
<?php
$data = date(j/m/Y);
$hora = date(H:i:s);
77
APOSTILA DE PHP
$data = date(Y/m/j);
htmlspecialchars
htmlentities
para º
para ª
para á
para ç
78
APOSTILA DE PHP
nl2br
Imprime:
Maurcio<br>Vivas<br>
get_meta_tags
Exemplo:
No arquivo teste.html temos:
...
<head>
<meta name=author content=jose>
<meta name=tags content=php3 documentation>
...
</head><! busca encerra aqui >
...
a execuo da funo:
get_meta_tags(teste.html);
Devolve o array:
array(author=>jose,tags=>php3 documentation);
79
APOSTILA DE PHP
strip_tags
urlencode
urldecode
Implode e join
80
APOSTILA DE PHP
Exemplo:
split
explode
81
APOSTILA DE PHP
similar_text
Exemplo:
strcasecmp
strcmp
82
APOSTILA DE PHP
strstr
stristr
strpos
strrpos
83
APOSTILA DE PHP
chop
ltrim
trim
strrev
84
APOSTILA DE PHP
strtolower
strtoupper
ucfirst
ucwords
85
APOSTILA DE PHP
str_replace
FUNES DIVERSAS
chr
ord
echo
strlen
86
APOSTILA DE PHP
Referncia/fontes bibliogrficas:
www.php.net
www.phpbuilder.com
www.phpwizard.net
87
APOSTILA DE PHP
Anotaes
88
APOSTILA DE PHP
Anotaes
89
APOSTILA DE PHP
Anotaes
90
APOSTILA DE PHP
Anotaes
91
APOSTILA DE PHP
Anotaes
92
APOSTILA DE PHP
Anotaes
93
APOSTILA DE PHP
Anotaes
94
APOSTILA DE PHP
Anotaes
95
APOSTILA DE PHP
Anotaes
96
APOSTILA DE PHP
Anotaes
97
APOSTILA DE PHP
Anotaes
98
APOSTILA DE PHP
99
APOSTILA DE PHP
100