Apostila de PHP
Apostila de PHP
Apostila de PHP
SUMÁRIO
1. PHP ................................................................................... 02
1.1 Como surgiu .................................................................. 02
1.2 O que pode ser feito........................................................ 02
2. Características do PHP....................................................... 03
2.1 Custo ............................................................................ 03
2.2 Código fonte aberto ........................................................ 04
2.3 Licença.......................................................................... 05
2.4 Adequação..................................................................... 06
3. Estudo comparativo entre ASP e PHP ................................ 07
4. Banco de dados MySQL ou PostgreSQL .............................. 09
5. Instalação ......................................................................... 09
5.1 Windows........................................................................ 09
5.2 Linux ............................................................................ 11
6. Exemplo prático................................................................. 13
6.1 Criando as tabelas .......................................................... 14
6.2 Área administrativa ......................................................... 18
6.2.1 Página inicial (index.php) ........................................... 18
6.2.2 Página com as opções (opcoes.php)............................. 20
6.2.3 Cadastro de Clientes (cadclientes.php) ......................... 21
6.2.4 Gerenciamento de clientes (gerlientes.php) .................. 25
6.2.5 Alteração dos dados do cliente(altclientes.php).............. 28
6.2.6 Exclusão do cliente (excluirclientes.php)....................... 32
7. Considerações finais .......................................................... 33
7.1 Conclusão ...................................................................... 33
7.2 Referências bibliográficas ................................................. 34
2
PHP
2. Características do PHP
2.1 Custo
Como pode-se ver o PHP é o único que não tem custo nenhum
tanto para desenvolvimento quanto para o servidor pois eles são
totalmente gratuitos bastando apenas que se baixe da Internet.
2.3 Licença
2.4 Adequação
HTML
ainda contém alguns bugs, bem com uma perfomance baixa de páginas
ASP rodando fora dos servidores da Microsoft.
O ASP ele tem uma interface padronizada a DB’S pelo ADO ou seja
pode-se começar um projeto utilizando um determinado banco de dados
e no meio do caminho ou depois trocar de banco sem ter que alterar
nenhuma linha de código, bastando apenas que se entre no sistema de
ODBC e mudar as propriedades de conexão que existia lá. No PHP isso
não seria possível, portanto seria necessário a mudança do código para
a alteração do banco de dados a ser utilizado.
5. Instalação
5.1 Windows
1. MySQL
A instalação é muito simples, basta você baixá-lo em
http://www.mysql.com e executar o programa setup.exe. Feito a
instalação o MySQL já estará funcional. Para ativá-lo no Win9x, execute
o comando mysqld (dentro do diretório mysql/bin). Já no NT/2000 você
precisa executar os comandos:
C:\mysql\bin\mysqld-nt -install
NET START mysql
2 – Apache e PHP
- Faça o download do Apache e do PHP em: www.apache.org e
www.php.net respectivamente.
<?
echo phpinfo();
?>
http://localhost/index.php
5.2 Linux
1. MySQL
Baixe o MySQL em www.mysql.com, depois siga os passos abaixo:
14
- Inicialize o MySQL
# bin/safe_mysqld –user=mysql &
2- Apache e PHP
Baixe os arquivos de instalação em www.apache.org e www.php.net
respectivamente.
6. Exemplo prático
Cadastro de clientes
Área do nosso sistema para a inclusão de novos clientes. Abaixo,
segue a estrutura da nossa tabela.
tb_clientes
- id_user Æ Número auto – incremento, vai ser a nossa chave primária
- inclusao_user Æ Data e horário do cadastro do cliente
- user Æ apelido do cliente
- senha Æ senha do cliente
- nome_user Æ Nome completo
- end_user Æ Endere
- bairro_user Æ Bairro
- email_user Æ Email
- tel_user Æ Telefone
- cidade_user Æ Cidade
- estado_user Æ Código do Estado
end_user varchar(80),
bairro_user varchar(40),
email_user varchar(90),
tel_user varchar(25),
cidade_user varchar(80),
estado_user int
);
Arquivo: conecta.php
<?
$dbname="imasters";
21
$usuario="";
$password="";
Código fonte:
<?
include "conecta.php"; //Arquivo que conecta com o MySQL
if(mysql_num_rows($sql) > 0) {
$id_imasters = mysql_result($sql,0,"id_user");
$apelido_imasters = mysql_result($sql,0,"apelido");
$senha_imasters = mysql_result($sql,0,"senha");
session_register("id_imasters","apelido_imasters","senha_imas
ters"); //Registra as variáveis na sessão
23
<tr>
<td width="33%" height="25"><font face="Arial"
size="2">Apelido:</font></td>
<td width="67%" height="25"><font face="Arial" size="2">
<input type="text" name="apelido_login"></font></td>
</tr>
<tr>
<td width="33%" height="25"><font face="Arial"
size="2">Senha:</font></td>
<td width="67%" height="25"><font face="Arial"
size="2"><input type="password"
name="senha_login"></font></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="entrar"
value="Entrar >>"></td>
</tr>
</table>
</form>
</body>
</html>
24
As opções são:
- Cadastrar clientes
- Gerenciar clientes
Código fonte:
<?
include "conecta.php" //Conecta com a nosso banco de
dados MySQL
include “ver_sessao.php” //Verifica se a sessão está
ativa
?>
<html>
<head>
<title>Tutorial iMasters</title>
</head>
<?
if($acao == 'cadastrar') { /*Cadastra o cliente depois
que o formulário for enviado */
//Verifica os dados enviados
if($nome_user == '') {
$erros++;
$html_erros = $html_erros."<br>Nome";
}
if($end_user == '') {
$erros++;
$html_erros = $html_erros."<br>Endereço";
}
if($bairro_user == '') {
$erros++;
27
$html_erros = $html_erros."<br>Bairro";
}
if($email_user == '') {
$erros++;
$html_erros = $html_erros."<br>Email";
}
if($tel_user == '') {
$erros++;
$html_erros = $html_erros."<br>Telefone";
}
if($cidade_user == '') {
$erros++;
$html_erros = $html_erros."<br>Cidade";
}
if($estado_user == 0) {
$erros++;
$html_erros = $html_erros."<br>Estado";
}
'$email_user','$tel_user','$cidade_user','$estado_user')",$co
n)
or die("Erro no comando SQL:".mysql_error());
}//fecha else
} /*fecha acao= cadastrar*/ ?>
<?
if($acao == 'entrar') { /*Mostra o formulário de cadastro
de clientes */
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Endereço:</font></td>
<td height="25" width="76%"><font face="Arial"
size="2">
<input type="text" name="end_user"
size="30"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Bairro:</font></td>
<td height="25" width="76%"><font face="Arial"
size="2">
<input type="text" name="bairro_user"
size="30"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Email:</font></td>
29
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Telefone:</font></td>
<td height="25" width="76%"><font face="Arial"
size="2">
<input type="text" name="tel_user"
size="20"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Cidade:</font></td>
<td height="25" width="76%"><font face="Arial"
size="2">
<input type="text" name="cidade_user"
size="35"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Estado:</font></td>
<td height="25" width="76%"><font face="Arial"
size="2">
<select name="estado_user">
<option value="0"><< Selecione o estado >></option>
<?while($array = mysql_fetch_array($sql_estados))
{?>
<option value="<?echo
$array['id_estado'];?>"><?echo $array['estado'];?></option>
<?}?>
</select></font></td>
</tr>
<tr>
<td height="25" colspan="2">
<div align="center">
<input type="submit" name="cadastrar"
value="Cadastrar cliente >>"></div></td>
</tr>
</table>
</form>
30
'$email_user','$tel_user','$cidade_user','$estado_user')",$co
n)
or die("Erro no comando SQL:".mysql_error());
Código fonte:
<?
include "conecta.php"; //Conecta com a nosso banco de dados
MySQL
include "ver_sessao.php"; //Verifica se a sessão está ativa
?>
<html>
<head>
<title>Tutorial iMasters</title>
</head>
$sql_cliente = "SELECT
id_user,date_format(inclusao_user,'%d/%m/%Y - %H:%i') as
inclusao_user, nome_user,cidade_user,uf FROM
tb_clientes,tb_estados WHERE tb_estados.id_estado =
tb_clientes.estado_user";
if($pesquisar == 'sim')
$sql_cliente = $sql_cliente." AND nome_user LIKE
'%$pesq%'";
?>
<br>
<table width="60%" border="0" cellspacing="0"
cellpadding="0" align="center">
<tr>
<td height="60">
<div align="center"><font face="Arial"
size="4"><b>Gerenciamento de Clientes</b></font></div></td>
</tr>
</table>
<br>
<form name="frm_pesq" method="post" action="<?echo
$PHP_SELF?>">
<table width="75%" border="0" cellspacing="1"
cellpadding="0" align="center">
<tr bgcolor="#6699CC">
<td colspan="2">
<div align="center"><font face="Arial"
size="2"><b>Pesquisa</b></font></div></td>
</tr>
<tr bgcolor="ebebeb">
<td width="32%"><font face="Arial" size="2">Nome a ser
procurado:</font></td>
<td width="68%"> <font face="Arial" size="2"><input
type="text" name="pesq" size="25">
<input type="submit" name="pesq" value="Pesquisar
>>">
<input type="hidden" name="pesquisar"
value="sim"></font></td>
</tr>
</table>
33
</form>
<br>
<?if(mysql_num_rows($sql_cliente) > 0) {?>
/
<?echo $array_cliente['uf'];?>
</font></td>
<td width="13%" height="25">
<div align="center"><font face="Arial" size="2">[ <a
href='altclientes.php?id_cliente=<?echo
$array_cliente['id_user'];?>&acao=entrar'>Alterar</a>
]</font></div>
</td>
<td width="12%" height="25">
<div align="center"><font face="Arial" size="2">[ <a
href='excluirclientes.php?id_cliente=<?echo
$array_cliente['id_user'];?>'>Excluir</a>
]</font></div>
</td>
</tr>
<?}?>
</table>
<?}/* fecha mysql_num_rows > 0 */
else{
echo "<br><br><div align=center><font face=Arial size=2>
Desculpe, mais não achei nada<br><br></font></div>";
}?>
<br><div align=center><font face=Arial size=2>
<a href='opcoes.php'>[ Voltar para o menu de opções
]</a></font></div>
</body>
</html>
if($pesquisar == 'sim')
$sql_cliente = $sql_cliente." AND nome_user LIKE
'%$pesq%'";
Código fonte:
<?
include "conecta.php" //Conecta com a nosso banco de dados
MySQL
include “ver_sessao.php” //Verifica se a sessão está ativa
?>
<html>
<head>
<title>Tutorial iMasters</title>
</head>
<?
if($acao == 'alterar') { /*Cadastra o cliente depois que o
formulário for enviado */
//Verifica os dados enviados
if($nome_user == '') {
$erros++;
$html_erros = $html_erros."<br>Nome";
}
if($end_user == '') {
$erros++;
$html_erros = $html_erros."<br>Endereço";
}
if($bairro_user == '') {
$erros++;
$html_erros = $html_erros."<br>Bairro";
}
if($email_user == '') {
$erros++;
$html_erros = $html_erros."<br>Email";
}
if($tel_user == '') {
$erros++;
$html_erros = $html_erros."<br>Telefone";
}
if($cidade_user == '') {
$erros++;
$html_erros = $html_erros."<br>Cidade";
}
if($estado_user == 0) {
$erros++;
37
$html_erros = $html_erros."<br>Estado";
}
cidade_user='$cidade_user',estado_user='$estado_user' WHERE
id_user='$id_cliente'")
or die("Erro no comando SQL:".mysql_error());
<?
if($acao == 'entrar') { /*Mostra o formulário de alteração
dos dados do cliente */
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Endereço:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<input type="text" name="end_user" size="30"
value="<?echo $array_cliente['end_user'];?>"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Bairro:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<input type="text" name="bairro_user" size="30"
value="<?echo $array_cliente['bairro_user'];?>"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Email:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<input type="text" name="email_user" size="35"
value="<?echo $array_cliente['email_user'];?>"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Telefone:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<input type="text" name="tel_user" size="20"
value="<?echo $array_cliente['tel_user'];?>"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Cidade:</font></td>
39
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Estado:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<select name="estado_user">
<option value="0"><< Selecione o estado >></option>
<?
while($array = mysql_fetch_array($sql_estados)) {
$estado_cliente = $array_cliente['estado_user'];
$cod_estado = $array['id_estado'];
$estado = $array['estado'];
if($estado_cliente == $cod_estado)
echo "<option value='$estado_cliente'
selected>$estado</option>";
else
echo "<option value='$cod_estado'>$estado</option>";
}?>
</select></font></td>
</tr>
<tr>
<td height="25" colspan="2">
<div align="center">
<input type="submit" name="alterar" value="Alterar
dados >>">
<input type="hidden" name="id_cliente"
value="<?echo $array_cliente['id_user'];?>">
</div></td>
</tr>
</table>
</form>
<?
} /*fecha acao=entrar */
?>
</body>
</html>
cidade_user='$cidade_user',estado_user='$estado_user' WHERE
id_user='$id_cliente'")
or die("Erro no comando SQL:".mysql_error());
?>
41
Código fonte:
<?
include "conecta.php"; //Conecta com o banco de dados MySQL
include "ver_sessao.php"; //Verifica se a sessão está ativa
7. Considerações finais
7.1 Conclusão
Até a próxima
Júlio César Martini
Colunista PHP / MySQL
códigos
ALTCLIENTE
<?
//=========================================
// Sistema desenvolvido para o iMasters
// by: Júlio César Martini
// email: baphp@imasters.com.br
<html>
<head>
<title>Tutorial iMasters</title>
</head>
<?
if($acao == 'alterar') { /*Cadastra o cliente depois que o formulário for
enviado */
//Verifica os dados enviados
if($nome_user == '') {
$erros++;
$html_erros = $html_erros."<br>Nome";
}
if($end_user == '') {
$erros++;
$html_erros = $html_erros."<br>Endereço";
45
if($bairro_user == '') {
$erros++;
$html_erros = $html_erros."<br>Bairro";
}
if($email_user == '') {
$erros++;
$html_erros = $html_erros."<br>Email";
}
if($tel_user == '') {
$erros++;
$html_erros = $html_erros."<br>Telefone";
}
if($cidade_user == '') {
$erros++;
$html_erros = $html_erros."<br>Cidade";
}
if($estado_user == 0) {
$erros++;
$html_erros = $html_erros."<br>Estado";
}
if($erros == 0) {
$sql = mysql_query("UPDATE tb_clientes SET
nome_user='$nome_user',end_user='$end_user',
46
bairro_user='$bairro_user',email_user='$email_user',tel_user='$tel_use
r',
cidade_user='$cidade_user',estado_user='$estado_user' WHERE
id_user='$id_cliente'")
or die("Erro no comando SQL:".mysql_error());
<?
if($acao == 'entrar') { /*Mostra o formulário de alteração dos dados do
cliente */
$array_cliente = mysql_fetch_array($sql_cliente);
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Endereço:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<input type="text" name="end_user" size="30" value="<?echo
$array_cliente['end_user'];?>"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Bairro:</font></td>
48
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Email:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<input type="text" name="email_user" size="35" value="<?echo
$array_cliente['email_user'];?>"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Telefone:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<input type="text" name="tel_user" size="20" value="<?echo
$array_cliente['tel_user'];?>"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Cidade:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<input type="text" name="cidade_user" size="35" value="<?echo
$array_cliente['cidade_user'];?>"></font></td>
</tr>
<tr>
49
<tr>
<td height="25" colspan="2">
<div align="center">
<input type="submit" name="alterar" value="Alterar dados
>>">
<input type="hidden" name="id_cliente" value="<?echo
$array_cliente['id_user'];?>">
</div></td>
</tr>
</table>
</form>
50
Cadastro de Clientes
<?
//=========================================
// Sistema desenvolvido para o iMasters
// by: Júlio César Martini
// email: baphp@imasters.com.br
<tr>
<td height="60">
<div align="center"><font face="Arial" size="4"><b>Cadastro de
Clientes</b></font></div></td>
</tr>
</table>
<br>
<?
if($acao == 'cadastrar') { /*Cadastra o cliente depois que o formulário
for enviado */
//Verifica os dados enviados
if($nome_user == '') {
$erros++;
$html_erros = $html_erros."<br>Nome";
}
if($end_user == '') {
$erros++;
$html_erros = $html_erros."<br>Endereço";
}
if($bairro_user == '') {
$erros++;
$html_erros = $html_erros."<br>Bairro";
}
if($email_user == '') {
$erros++;
$html_erros = $html_erros."<br>Email";
52
if($tel_user == '') {
$erros++;
$html_erros = $html_erros."<br>Telefone";
}
if($cidade_user == '') {
$erros++;
$html_erros = $html_erros."<br>Cidade";
}
if($estado_user == 0) {
$erros++;
$html_erros = $html_erros."<br>Estado";
}
if($erros == 0) {
$sql = mysql_query("INSERT INTO
tb_clientes(inclusao_user,nome_user,end_user,bairro_user,email_user,
tel_user,cidade_user,estado_user)
VALUES(now(),'$nome_user','$end_user','$bairro_user',
'$email_user','$tel_user','$cidade_user','$estado_user')")
or die("Erro no comando SQL:".mysql_error());
else {
echo "<div align=center><font face=Arial
size=2><b>ATENÇÃO</b><br><br>Foram encontrados
<b>$erros</b>
erro(s) no cadastro do cliente:<br><b>$html_erros</b>
<br><br><a href='javascript:history.go(-1)'><<
Voltar</a></font></div><br><br>";
}//fecha else
} /*fecha acao= cadastrar*/ ?>
<?
if($acao == 'entrar') { /*Mostra o formulário de cadastro de clientes */
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Endereço:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<input type="text" name="end_user" size="30"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Bairro:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<input type="text" name="bairro_user" size="30"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Email:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<input type="text" name="email_user" size="35"></font></td>
</tr>
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Telefone:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<input type="text" name="tel_user" size="20"></font></td>
</tr>
<tr>
55
<tr>
<td height="25" width="24%"><font face="Arial"
size="2">Estado:</font></td>
<td height="25" width="76%"><font face="Arial" size="2">
<select name="estado_user">
<option value="0"><< Selecione o estado >></option>
<?while($array = mysql_fetch_array($sql_estados)) {?>
<option value="<?echo $array['id_estado'];?>"><?echo
$array['estado'];?></option>
<?}?>
</select></font></td>
</tr>
<tr>
<td height="25" colspan="2">
<div align="center">
<input type="submit" name="cadastrar" value="Cadastrar cliente
>>"></div></td>
</tr>
</table>
</form>
<?} /*fecha acao=entrar */?>
</body>
</html>
56
GerClientes
<?
//=========================================
// Sistema desenvolvido para o iMasters
// by: Júlio César Martini
// email: baphp@imasters.com.br
if($pesquisar == 'sim')
$sql_cliente = $sql_cliente." AND nome_user LIKE '%$pesq%'";
?>
<br>
<table width="60%" border="0" cellspacing="0" cellpadding="0"
align="center">
<tr>
<td height="60">
<div align="center"><font face="Arial" size="4"><b>Gerenciamento
de Clientes</b></font></div></td>
</tr>
</table>
<br>
<form name="frm_pesq" method="post" action="<?echo
$PHP_SELF?>">
<table width="75%" border="0" cellspacing="1" cellpadding="0"
align="center">
<tr bgcolor="#6699CC">
<td colspan="2">
<div align="center"><font face="Arial"
size="2"><b>Pesquisa</b></font></div></td>
</tr>
58
<tr bgcolor="ebebeb">
<td width="32%"><font face="Arial" size="2">Nome a ser
procurado:</font></td>
<td width="68%"> <font face="Arial" size="2"><input type="text"
name="pesq" size="25">
<input type="submit" name="pesq" value="Pesquisar >>">
<input type="hidden" name="pesquisar"
value="sim"></font></td>
</tr>
</table>
</form>
<br>
<?if(mysql_num_rows($sql_cliente) > 0) {?>
Index
61
<?
//=========================================
// Sistema desenvolvido para o iMasters
// by: Júlio César Martini
// email: baphp@imasters.com.br
if(mysql_num_rows($sql) > 0) {
$id_imasters = mysql_result($sql,0,"id_user");
$apelido_imasters = mysql_result($sql,0,"apelido");
$senha_imasters = mysql_result($sql,0,"senha");
}
}
?>
<html>
<head>
<title>Tutorial iMasters</title>
</head>
<tr>
<td width="33%" height="25"><font face="Arial"
size="2">Apelido:</font></td>
<td width="67%" height="25"><font face="Arial" size="2">
<input type="text" name="apelido_login"></font></td>
</tr>
<tr>
<td width="33%" height="25"><font face="Arial"
size="2">Senha:</font></td>
<td width="67%" height="25"><font face="Arial" size="2"><input
type="password" name="senha_login"></font></td>
63
</tr>
<tr>
<td colspan="2"><input type="submit" name="entrar"
value="Entrar >>"></td>
</tr>
</table>
</form>
</body>
</html>
OPÇõES
<?
//=========================================
// Sistema desenvolvido para o iMasters
// by: Júlio César Martini
// email: baphp@imasters.com.br
<html>
64
<head>
<title>Tutorial iMasters</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
</head>
</table>
</body>
</html>
Conecta
<?
//=========================================
// Sistema desenvolvido para o iMasters
// by: Júlio César Martini
// email: baphp@imasters.com.br
// Conexão
//=========================================
$dbname="imasters";
$usuario="";
$password="";
</strong></big></p>";
exit;
}
Excluir Clientes
<?
//=========================================
// Sistema desenvolvido para o iMasters
// by: Júlio César Martini
// email: baphp@imasters.com.br
?>
Ver Seção
<?
session_start("imasters");
if(!(session_is_registered("id_imasters") AND
session_is_registered("apelido_imasters") AND
session_is_registered("senha_imasters"))) {
echo "Essa é uma área restrita";
exit;
}
?>