Estou fazendo um cadastro simples usando CRUD, comecei a programar a pouco tempo e está sendo minha primeira experiencia com CRUD.
fiz um pequeno cadastro e estou alterando para implementar aos poucos. Com uma dessas alterações os botões que eu adicionei perderam suas funcionalidades.
Segue o código:
<?php
// Verificar se foi enviando dados via POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = (isset($_POST["id"]) && $_POST["id"] != null) ? $_POST["id"] : "";
$nome = (isset($_POST["nome"]) && $_POST["nome"] != null) ? $_POST["nome"] : "";
$email = (isset($_POST["email"]) && $_POST["email"] != null) ? $_POST["email"] : "";
$celular = (isset($_POST["celular"]) && $_POST["celular"] != null) ? $_POST["celular"] : NULL;
$cidade = (isset($_POST["cidade"]) && $_POST["cidade"] != null) ? $_POST["cidade"] : NULL;
$estado = (isset($_POST["estado"]) && $_POST["estado"] != null) ? $_POST["estado"] : NULL;
} else if (!isset($id)) {
// Se não se não foi setado nenhum valor para variável $id
$id = (isset($_GET["id"]) && $_GET["id"] != null) ? $_GET["id"] : "";
$nome = NULL;
$email = NULL;
$celular = NULL;
$cidade = NULL;
$estado = NULL;
}
try {
$conexao = new PDO("mysql:host=localhost;port=3307;dbname=crudsimples", "root", "usbw");
$conexao->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conexao->exec("set names utf8");
} catch (PDOException $erro) {
echo "Erro na conexão:" . $erro->getMessage();
}
if (isset($_REQUEST["act"]) && $_REQUEST["act"] == "save" && $nome != "") {
try {
$stmt = $conexao->prepare("INSERT INTO contatos (nome, email, celular, cidade, estado) VALUES (?, ?, ?, ?, ?)");
$stmt->bindParam(1, $nome);
$stmt->bindParam(2, $email);
$stmt->bindParam(3, $celular);
$stmt->bindParam(4, $cidade);
$stmt->bindParam(5, $estado);
if ($stmt->execute()) {
if ($stmt->rowCount() > 0) {
echo "Dados cadastrados com sucesso!";
$id = null;
$nome = null;
$email = null;
$celular = null;
$cidade = null;
$estado = null;
} else {
echo "Erro ao tentar efetivar cadastro";
}
} else {
throw new PDOException("Erro: Não foi possível executar a declaração sql");
}
} catch (PDOException $erro) {
echo "Erro: " . $erro->getMessage();
}
}
if (isset($_REQUEST["act"]) && $_REQUEST["act"] == "upd" && $id != "") {
try {
$stmt = $conexao->prepare("SELECT * FROM contatos WHERE id = ?");
$stmt->bindParam(1, $id, PDO::PARAM_INT);
if ($stmt->execute()) {
$rs = $stmt->fetch(PDO::FETCH_OBJ);
$id = $rs->id;
$nome = $rs->nome;
$email = $rs->email;
$celular = $rs->celular;
$cidade = $rs->cidade;
$estado = $rs->estado;
} else {
throw new PDOException("Erro: Não foi possível executar a declaração sql");
}
} catch (PDOException $erro) {
echo "Erro: ".$erro->getMessage();
}
}
if ($id != "") {
$stmt = $conexao->prepare("UPDATE contatos SET nome=?, email=?, celular=? cidade=?, estado=? WHERE id = ?");
$stmt->bindParam(5, $id);
} else {
$stmt = $conexao->prepare("INSERT INTO contatos (nome, email, celular, cidade, estado) VALUES (?, ?, ?, ?, ?)");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css" href="cadastro.css" />
<title>Cadastro em reforma.</title>
</head>
<body>
<h1>Cadastro Simples.</h1>
<form action="?act=save" method="POST" name="form1" >
<hr>
<input type="hidden" name="id" <?php
// Preenche o id no campo id com um valor "value"
if (isset($id) && $id != null || $id != "") {
echo "value=\"{$id}\"";
}
?> />
<table>
<tr>
Nome:
<input type="text" name="nome" <?php
// Preenche o nome no campo nome com um valor "value"
if (isset($nome) && $nome != null || $nome != ""){
echo "value=\"{$nome}\"";
}
?> />
</tr>
</table>
<table>
<tr>
E-mail:
<input type="text" name="email" <?php
// Preenche o email no campo email com um valor "value"
if (isset($email) && $email != null || $email != ""){
echo "value=\"{$email}\"";
}
?> />
</tr>
</table>
<table>
<tr>
Celular:
<input type="text" name="celular" <?php
// Preenche o celular no campo celular com um valor "value"
if (isset($celular) && $celular != null || $celular != ""){
echo "value=\"{$celular}\"";
}
?> />
<table>
<tr>
Cidade:
<input type="text" name="cidade" <?php
// Preenche a cidade no campo nome com um valor "value"
if (isset($cidade) && $cidade != null || $cidade != ""){
echo "value=\"{$cidade}\"";
}
?> />
Estado:
<input type="text" name="estado" <?php
// Preenche o estado no campo nome com um valor "value"
if (isset($estado) && $estado != null || $estado != ""){
echo "value=\"{$estado}\"";
}
if (isset($_REQUEST["act"]) && $_REQUEST["act"] == "del" && $id != "") {
try {
$stmt = $conexao->prepare("DELETE FROM contatos WHERE id = ?");
$stmt->bindParam(1, $id, PDO::PARAM_INT);
if ($stmt->execute()) {
echo "Registo foi excluído com êxito";
$id = null;
} else {
throw new PDOException("Erro: Não foi possível executar a declaração sql");
}
} catch (PDOException $erro) {
echo "Erro: ".$erro->getMessage();
}
}
?> />
<br> <input type="submit" value="Salvar" />
<input type="reset" value="Novo" />
</br>
<hr>
</form>
<table border="1" width="100%">
<tr>
<th>Nome</th>
<th>E-mail</th>
<th>Celular</th>
<th>Cidade</th>
<th>Estado</th>
<th>Ações</th>
</tr>
<?php
try {
$stmt = $conexao->prepare("SELECT * FROM contatos");
if ($stmt->execute()) {
while ($rs = $stmt->fetch(PDO::FETCH_OBJ)) {
echo "<tr>";
echo "<td>".$rs->nome."</td>
<td>".$rs->email."</td>
<td>".$rs->celular."</td>
<td>".$rs->cidade."</td>
<td>".$rs->estado."</td>
<td>
<center>
<a href=\"?act=upd&id=" . $rs->id . "\">[Alterar]</a>"
." "
."<a href=\"?act=del&id=" . $rs->id . "\">[Excluir]</a>
</center>
</td>";
echo "</tr>";
}
} else {
echo "Erro: Não foi possível recuperar os dados do banco de dados";
}
} catch (PDOException $erro) {
echo "Erro: ".$erro->getMessage();
}
?>
</table>
</body>
</html>
Por algum motivo minha tabela no Phpmyadmin também mudou e não consigo mais editar. Exclui a "id" e depois adicionei novamente e começou os problemas. Agradeço a ajuda desde já.