Colocar Resposta 
 
Avaliação do Tópico:
  • 0 votos - 0 Média
  • 1
  • 2
  • 3
  • 4
  • 5
[tuturial] sistema de cadastro com PHP e MYSQL agora com ficheiro ZIP
01-08-2008, 19:15 (Esta mensagem foi modificada pela última vez a: 02-08-2008 10:35 por guerreiro.)
Mensagem: #1
[tuturial] sistema de cadastro com PHP e MYSQL agora com ficheiro ZIP
tabela.sql
Código:
CREATE TABLE usuarios (
id_usuario SMALLINT ( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
nome VARCHAR ( 45 ) NOT NULL,
email VARCHAR ( 64 ) NOT NULL UNIQUE,
data_nascimento DATE NOT NULL,
sexo ENUM ( 'M', 'F' ) NOT NULL,
preferencias SET ( 'R', 'S', 'P', 'F' ) NOT NULL COMMENT 'R=Romance;S=Suspense;P=Policial;F=Ficção',
salario DECIMAL ( 10,2 ) NOT NULL,
endereco VARCHAR ( 30 ) NOT NULL,
bairro VARCHAR ( 20 ) NOT NULL,
cidade VARCHAR ( 45 ) NOT NULL,
fk_estado SMALLINT ( 5 ) UNSIGNED NOT NULL,
login VARCHAR ( 40 ) NOT NULL,
senha CHAR ( 32 ) NOT NULL
);

CREATE TABLE estados (
id_estado SMALLINT ( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
uf CHAR ( 2 ) NOT NULL,
estado VARCHAR ( 19 ) NOT NULL UNIQUE
);

INSERT INTO estados VALUES ( NULL , "AC", "Acre");
INSERT INTO estados VALUES ( NULL , "AL", "Alagoas");
INSERT INTO estados VALUES ( NULL , "AP", "Amapá");
INSERT INTO estados VALUES ( NULL , "AM", "Amazonas");
INSERT INTO estados VALUES ( NULL , "BA", "Bahia");
INSERT INTO estados VALUES ( NULL , "CE", "Ceará");
INSERT INTO estados VALUES ( NULL , "DF", "Distrito Federal");
INSERT INTO estados VALUES ( NULL , "ES", "Espirito Santo");
INSERT INTO estados VALUES ( NULL , "GO", "Goiás");
INSERT INTO estados VALUES ( NULL , "MA", "Maranhão");
INSERT INTO estados VALUES ( NULL , "MT", "Mato Grosso");
INSERT INTO estados VALUES ( NULL , "MS", "Mato Grosso do Sul");
INSERT INTO estados VALUES ( NULL , "MG", "Minas Gerais");
INSERT INTO estados VALUES ( NULL , "PA", "Pará");
INSERT INTO estados VALUES ( NULL , "PB", "Paraíba");
INSERT INTO estados VALUES ( NULL , "PR", "Paraná");
INSERT INTO estados VALUES ( NULL , "PE", "Pernambuco");
INSERT INTO estados VALUES ( NULL , "PI", "Piauí");
INSERT INTO estados VALUES ( NULL , "RN", "Rio Grande do Norte");
INSERT INTO estados VALUES ( NULL , "RS", "Rio Grande do Sul");
INSERT INTO estados VALUES ( NULL , "RJ", "Rio de Janeiro");
INSERT INTO estados VALUES ( NULL , "RO", "Rondônia");
INSERT INTO estados VALUES ( NULL , "RR", "Roraima");
INSERT INTO estados VALUES ( NULL , "SC", "Santa Catarina");
INSERT INTO estados VALUES ( NULL , "SP", "São Paulo");
INSERT INTO estados VALUES ( NULL , "SE", "Sergipe");
INSERT INTO estados VALUES ( NULL , "TO", "Tocantins");


index.html

Código:
<a href="cadastro.php">Cadastrar Usuarios</a><br />
<a href="listar.php">Listar Usuarios</a>

cadastro.php

Código:
<?php
//Verifico se o arquivo existe
if(file_exists("init.php")) {
require "init.php";
} else {
echo "Arquivo init.php nao foi encontrado";
exit;
}
//verifico se a função que eu criei existe, vai que alguem pegou meu script e apagou ela = )
if(!function_exists("Abre_Conexao")) {
echo "Erro o arquivo init.php foi auterado, nao existe a função Abre_Conexao";
exit;
}

Abre_Conexao();
$re = mysql_query("select * from estados order by estado");
//verifico se nao deu erro de mysql
if(mysql_errno() != 0) {
//verifico se a $errros existe, mesma coisa vai que alguem meche no script e apagou ela
if(!isset($erros)) {
echo "Erro o arquivo init.php foi auterado, nao existe \$erros";
exit;
}
echo $erros[mysql_errno()];
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Cadastro</title>
<style>
<!--
.textBox { border:1px solid gray; width:200px;}
-->
</style>
</head>

<body>
<form id="form1" name="form1" method="post" action="salvar.php">
<table width="400" border="0" align="center">
<tr>
<td width="145">Nome</td>
<td width="245"><input name="nome" type="text" id="nome" maxlength="45" class="textBox" /></td>
</tr>
<tr>
<td>Email</td>
<td><input name="email" type="text" id="email" maxlength="64" class="textBox" /></td>
</tr>
<tr>
<td>Data Nascimento</td>
<td>
<?php
/*aqui eu criei uma função para montar o combo para mim, na propria função a seguir eu explico como ela funciona*/
echo monta_select("dia", 1, 31);
echo monta_select("mes", 1, 12);
echo monta_select("ano", 1940, 1988);
?>
</td>
</tr>
<tr>
<td>Sexo</td>
<td><input name="sexo" type="radio" value="M" checked="checked" /><label>Masculino</label>
<input name="sexo" type="radio" value="F" /> <label>Feminino</label></td>
</tr>
<tr>
<td>Preferencias de Filmes </td>
<td><select name="preferencias[]" class="textBox" multiple="multiple" id="preferencias">
<option value="R">Romance</option>
<option value="S">Suspense</option>
<option value="P">Policial</option>
<option value="F">Ficção</option>
</select>
</td>
</tr>
<tr>
<td>Salario</td>
<td><input name="salario" type="text" id="salario" maxlength="5" class="textBox" /></td>
</tr>
<tr>
<td>Endereco</td>
<td><input name="endereco" type="text" id="endereco" maxlength="30" class="textBox" /></td>
</tr>
<tr>
<td>Bairro</td>
<td><input name="bairro" type="text" id="bairro" maxlength="20" class="textBox" /></td>
</tr>
<tr>
<td>Cidade</td>
<td><input name="cidade" type="text" id="cidade" maxlength="45" class="textBox" /></td>
</tr>
<tr>
<td>Estado</td>
<td><select name="estados" id="estados" class="textBox" >
<?php
//pego os dados do banco para montar o combo do estados
while($l = mysql_fetch_array($re)) {
$id = $l["id_estado"];
$estado = $l["estado"];
$uf = $l["uf"];
echo "<option value=\"$id\">$uf - $estado</option>\n";
}
//fecho a conexao com o banco
@mysql_close();

?>
</select> </td>
</tr>
<tr>
<td>Login</td>
<td><input name="login" type="text" id="login" maxlength="40" class="textBox" /></td>
</tr>
<tr>
<td>Senha</td>
<td><input name="senha" type="password" id="senha" maxlength="10" class="textBox" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Salvar" style="cursor:pointer;" /></td>
</tr>
</table>
</form>
</body>
</html>

salvar.php
Código:
<?php
/*verifico se os dados estao vindos do formulario, porque se uma pessoa acessar essa pagina diretamente
poderia dar erro, entao eu testo antes*/
if($_SERVER["REQUEST_METHOD"] == "POST") {
$nome = $_POST["nome"];
$email = $_POST["email"];
$data = "{$_POST["ano"]}-{$_POST["mes"]}-{$_POST["dia"]}";
$sexo = $_POST["sexo"];
//if e else simplificado, verifico se foi escolhido alguma preferencia e crio um array
$preferencias = isset($_POST["preferencias"]) ? implode(",", $_POST["preferencias"]) : "";
$salario = $_POST["salario"];
$endereco = $_POST["endereco"];
$bairro = $_POST["bairro"];
$cidade = $_POST["cidade"];
$estados = $_POST["estados"];
$login = $_POST["login"];
$senha = $_POST["senha"];

//aqui ja expliquei, mas denovo: ele verifica se o arquivo existe
if(file_exists("init.php")) {
require "init.php";
} else {
echo "Arquivo init.php nao foi encontrado";
exit;
}
//ja expliquei, mas ultima vez: verifica se a função que eu vou usar existe
if(!function_exists("Abre_Conexao")) {
echo "Erro o arquivo init.php foi auterado, nao existe a função Abre_Conexao";
exit;
}

Abre_Conexao();
if(@mysql_query("INSERT INTO usuarios VALUES ( NULL , '$nome', '$email', '$data' , '$sexo',
'$preferencias', '$salario', '$endereco', '$bairro', '$cidade', '$estados', '$login', MD5( '$senha' ) )")) {
//verifiquei acima se deu certo o comando e aqui verifico se foi mesmo gravado o dado no banco
if(mysql_affected_rows() == 1){
echo "Registro efetuado com sucesso<br />";
}

} else {
//verifico se nao estao tentando gravar um dado que ja existe, pois usei UNIQUE na tabela
if(mysql_errno() == 1062) {
echo $erros[mysql_errno()];
exit;
} else {
echo "Erro nao foi possivel efetuar o cadastro";
exit;
}
@mysql_close();
}

}
?>
<a href="index.html">Voltar</a>


listar.php
Código:
<a href="index.html">Voltar</a>
<?php
if(file_exists("init.php")) {
require "init.php";
} else {
echo "Arquivo init.php nao foi encontrado";
exit;
}

if(!function_exists("Abre_Conexao")) {
echo "Erro o arquivo init.php foi auterado, nao existe a função Abre_Conexao";
exit;
}

Abre_Conexao();
$re = mysql_query("SELECT * FROM usuarios INNER JOIN estados ON usuarios.fk_estado = estados.id_estado ORDER BY usuarios.nome;");
if(mysql_errno() != 0) {
if(!isset($erros)) {
echo "Erro o arquivo init.php foi auterado, nao existe $erros";
exit;
}
echo $erros[mysql_errno()];
exit;
}
?>

<table width="100%" border="1">
<tr>
<td>Ações</td>
<td>Nome</td>
<td>Email</td>
<td>Data Nasc.</td>
<td>Sexo</td>
<td>Preferencias</td>
<td>salario</td>
<td>Endereço</td>
<td>Bairro</td>
<td>Cidade</td>
<td>Estado</td>
<td>Login</td>
</tr>
<?php
while($l = mysql_fetch_array($re)) {
$id = $l["id_usuario"];
$nome = $l["nome"];
$email = $l["email"];
$data = implode("/", array_reverse(explode("-", $l["data_nascimento"])));
$sexo = $l["sexo"] == "M" ? "Masculino" : "Feminino";
$preferencia = Pega_Preferencia($l["preferencias"]);
$salario = $l["salario"];
$endereco = $l["endereco"];
$bairro = $l["bairro"];
$cidade = $l["cidade"];
$estado = $l["estado"];
$login = $l["login"];

echo "
<tr>
<td><a href=\"editar.php?id=$id\">[Editar]</a> <a href=\"excluir.php?id=$id\">[Excluir]</a></td>
<td> $nome</td>
<td> $email</td>
<td> $data</td>
<td> $sexo</td>
<td> ". monta_combo($preferencia). "</td>
<td> ". number_format($salario, 2, ",", "."). "</td>
<td> $endereco</td>
<td> $bairro</td>
<td> $cidade</td>
<td> $estado</td>
<td> $login</td>
</tr>\n";
}
@mysql_close();
?>
</table>

editar.php

Código:
<?php
if(file_exists("init.php")) {
require "init.php";
} else {
echo "Arquivo init.php nao foi encontrado";
exit;
}

if(!function_exists("Abre_Conexao")) {
echo "Erro o arquivo init.php foi auterado, nao existe a função Abre_Conexao";
exit;
}
$id = $_GET["id"];

Abre_Conexao();
$re = mysql_query("select count(*) as total from usuarios where id_usuario = $id");
$total = mysql_result($re, 0, "total");

if($total == 1) {
$re = mysql_query("select * from usuarios, estados where estados.id_estado = usuarios.fk_estado and usuarios.id_usuario = $id");
$dados = mysql_fetch_array($re);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Cadastro</title>
<style>
<!--
.textBox { border:1px solid gray; width:200px;}
-->
</style>
</head>

<body>
<form id="form1" name="form1" method="post" action="salvar_edicao.php">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<table width="400" border="0" align="center">
<tr>
<td width="145">Nome</td>
<td width="245"><input name="nome" type="text" id="nome" maxlength="45" class="textBox" value="<?php echo $dados["nome"]; ?>" /></td>
</tr>
<tr>
<td>Email</td>
<td><input name="email" type="text" id="email" maxlength="64" class="textBox" value="<?php echo $dados["email"]; ?>" /></td>
</tr>
<tr>
<td>Data Nascimento</td>
<td>
<?php
$arr = explode("-", $dados["data_nascimento"]);

echo Seleciona_Item($arr[2], monta_select("dia", 1, 31));
echo Seleciona_Item($arr[1], monta_select("mes", 1, 12));
echo Seleciona_Item($arr[0], monta_select("ano", 1940, 1988));
?>
</td>
</tr>
<tr>
<td>Sexo</td>
<td><input name="sexo" type="radio" value="M" <?php echo $dados["sexo"] == "M" ? "checked=\"checked\"" : ""; ?> /><label>Masculino</label>
<input name="sexo" type="radio" value="F" <?php echo $dados["sexo"] == "F" ? "checked=\"checked\"" : ""; ?> /> <label>Feminino</label></td>
</tr>
<tr>
<td>Preferencias de Filmes </td>
<td><select name="preferencias[]" class="textBox" multiple="multiple" id="preferencias">
<?php
$combo = "<option value=\"R\">Romance</option>
<option value=\"S\">Suspense</option>
<option value=\"P\">Policial</option>
<option value=\"F\">Ficção</option>";

$arr = explode(",", $dados["preferencias"]);
for($i = 0; $i < count($arr); $i++) {
$combo = preg_replace("#<option value=\"{$arr[$i]}\">#is", "<option value=\"{$arr[$i]}\" selected=\"selected\">", $combo);
}
echo $combo;
?>

</select>
</td>
</tr>
<tr>
<td>Salario</td>
<td><input name="salario" type="text" id="salario" maxlength="5" class="textBox" /></td>
</tr>
<tr>
<td>Endereco</td>
<td><input name="endereco" type="text" id="endereco" maxlength="30" class="textBox" /></td>
</tr>
<tr>
<td>Bairro</td>
<td><input name="bairro" type="text" id="bairro" maxlength="20" class="textBox" /></td>
</tr>
<tr>
<td>Cidade</td>
<td><input name="cidade" type="text" id="cidade" maxlength="45" class="textBox" /></td>
</tr>
<tr>
<td>Estado</td>
<td><select name="estados" id="estados" class="textBox" >
<option value="0">Selecione</option>
<?php
$re = mysql_query("select * from estados order by estado");
if(mysql_errno() != 0) {
if(!isset($erros)) {
echo "Erro o arquivo init.php foi auterado, nao existe $erros";
exit;
}
echo $erros[mysql_errno()];
exit;
}
while($l = mysql_fetch_array($re)) {
$id = $l["id_estado"];
$estado = $l["estado"];
$uf = $l["uf"];
echo Seleciona_Item($dados["id_estado"], "<option value=\"$id\">$uf - $estado</option>");

}
@mysql_close();

?>
</select> </td>
</tr>
<tr>
<td>Login</td>
<td><input name="login" type="text" id="login" maxlength="40" class="textBox" /></td>
</tr>
<tr>
<td>Senha</td>
<td><input name="senha" type="password" id="senha" maxlength="10" class="textBox" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Salvar" style="cursor:pointer;" /></td>
</tr>
</table>
</form>
</body>
</html>


excluir.php

Código:
<?php
if($_SERVER["REQUEST_METHOD"] == "GET") {
if(file_exists("init.php")) {
    require "init.php";        
} else {
    echo "Arquivo init.php nao foi encontrado";
    exit;
}

if(!function_exists("Abre_Conexao")) {
    echo "Erro o arquivo init.php foi auterado, nao existe a função Abre_Conexao";
    exit;
}
$id = $_GET["id"];

Abre_Conexao();
if(mysql_query("delete from usuarios where id_usuario = $id")) {
    if(mysql_affected_rows() == 1){
        echo "Registro deletado com sucesso<br />";
    }    
}    
}

?>
<a href="listar.php">Voltar</a>

salvar_edicao.php


Código:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST["id"];
$nome = $_POST["nome"];
$email = $_POST["email"];
$data = "{$_POST["ano"]}-{$_POST["mes"]}-{$_POST["dia"]}";
$sexo = $_POST["sexo"];
$preferencias = isset($_POST["preferencias"]) ? implode(",", $_POST["preferencias"]) : "";
$salario = $_POST["salario"];
$endereco = $_POST["endereco"];
$bairro = $_POST["bairro"];
$cidade = $_POST["cidade"];
$estados = $_POST["estados"];
$login = $_POST["login"];
$senha = $_POST["senha"];

if(file_exists("init.php")) {
require "init.php";
} else {
echo "Arquivo init.php nao foi encontrado";
exit;
}

if(!function_exists("Abre_Conexao")) {
echo "Erro o arquivo init.php foi auterado, nao existe a função Abre_Conexao";
exit;
}

Abre_Conexao();
if(@mysql_query("UPDATE usuarios SET nome = '$nome',
email = '$email',
sexo = '$sexo',
preferencias = '$preferencias',
salario = '$salario',
endereco = '$endereco',
bairro = '$bairro',
cidade = '$cidade',
fk_estado = '$estados',
login = '$login',
senha = MD5( '$senha' ) WHERE id_usuario = $id")) {

if(mysql_affected_rows() == 1){
echo "Registro atualizado com sucesso";
}

} else {
if(mysql_errno() == 1062) {
echo $erros[mysql_errno()];
exit;
} else {
echo "Erro nao foi possivel efetuar a edição";
exit;
}
@mysql_close();
}

}
?>
<a href="listar.php">Voltar</a>



tutorial retirado de imasters


espero que vos seja util Smile

abraços



ALTERADO
_________________________
deixo aqui o ficheiro zip Tongue



.zip  Cadastro.zip (Tamanho: 8,03 KB / Downloads: 180)

[Imagem: 1138308553.jpg] Tongue
Visitar Website de este utilizador Procurar todas as mensagens deste utilizador
Citar esta mensagem numa resposta
Colocar Resposta 


Mensagem neste Tópico
[tuturial] sistema de cadastro com PHP e MYSQL agora com ficheiro ZIP - guerreiro - 01-08-2008 19:15

Saltar Fórum:


Utilizadores a ver este tópico: 1 Visitante(s)