How To Do
To enable editing you need a variable to select the user and leave their data in the form. First of all take all your PHP code and put before the HTML code.
Now start the variables going on HTML form:
$codigo = '';
$nome = '';
$sobrenome = '';
$email = '';
Enter a field for the user code in the form
<input type="hidden" name="codigo" value="<?=$codigo?>">
Don’t forget to pass the other variables in the attributes value
of the other camps.
Get that field on POST:
$codigo = filter_var($_POST["codigo"], FILTER_VALIDATE_INT);
Now when we check if there is a user in the bank, we also need to check if it is a new or editing, this can be done by checking the code:
$select = $mysqli->query("SELECT * FROM usuarios WHERE Email='$email'");
if($select) {
$row = $select->num_rows;
$f = $select->fetch_assoc(); // Popula os dados na variável
// Verifica se o código é diferênte (se for novo usuário ou outro irá funcionar para ambos)
if($row > 0 && $codigo !== intval($f['id'])) {
echo "<script> alert ('Já existe um usuário com esse e-mail'); </script>";
In the statement from Insert, we need to check if it is new or update, if it is new get the ID:
if (empty($codigo)) { // Verifica se é novo
$insert = $mysqli->query("INSERT INTO `usuarios`(`nome`, `sobrenome`, `email`, `senha`) VALUES ('$nome', '$sobrenome', '$email', '$senha')");
if($insert) {
$codigo = $mysqli->insert_id; // Pega o id gerado
echo "<script> alert ('Usuário registrado com sucesso!'); location.href='cadastrou.php' </script>";
And finally, generate the UPDATE:
} else {
$sql = "UPDATE `usuarios` SET
`nome` = '$nome',
`sobrenome` = '$sobrenome',
`email` = '$email',
`senha` = '$senha'
WHERE
`id` = $codigo";
$update = $mysqli->query($sql);
if($update) {
echo "<script> alert ('Usuário atualizado com sucesso!'); location.href='cadastrou.php' </script>";
} else {
$erro = true;
echo $mysqli->error;
}
}
To fetch a user’s data you can do using GET:
if (!empty($_GET['codigo']) && filter_var($_GET['codigo'], FILTER_VALIDATE_INT)){
$select = $mysqli->query("SELECT * FROM usuarios WHERE Email='$email'");
if($select) {
$row = $select->num_rows;
$f = $select->fetch_assoc();
if($row > 0) {
$codigo = $f['codigo'];
$nome = $f['nome'];
$sobrenome = $f['sobrenome'];
$email = $f['email'];
}
}
}
The above example works as follows: http://localhost/cadastro.php?codigo=1
Complete Code
<?php
$codigo = '';
$nome = '';
$sobrenome = '';
$email = '';
if(isset($_POST["button"])) {
$codigo = filter_var($_POST["codigo"], FILTER_VALIDATE_INT);
$nome = filter_var($_POST["nome"]);
$sobrenome = filter_var($_POST["sobrenome"]);
$email = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL);
$senha = $_POST["senha"]; // Considere criptografar a senha antes de inserir no banco
$csenha = $_POST["csenha"];
if ($email === false){
echo "<script> alert('E-mail inválido!'); </script>";
return true;
}
if($nome == "" || $sobrenome == "" || $email == "" || (empty($codigo) && ($senha == "" || $csenha == ""))) {
echo "<script> alert('Preencha todos os campos!'); </script>";
return true;
}
if ($senha != $csenha) {
echo "<script> alert ('As senhas devem ser iguais!'); </script>";
return true;
}
$erro = false;
$select = $mysqli->query("SELECT * FROM usuarios WHERE Email='$email'");
if($select) {
$row = $select->num_rows;
$f = $select->fetch_assoc();
if($row > 0 && $codigo !== intval($f['codigo'])) {
echo "<script> alert ('Já existe um usuário com esse e-mail'); </script>";
$erro = true;
} else {
if (empty($codigo)) {
$insert = $mysqli->query("INSERT INTO `usuarios`(`nome`, `sobrenome`, `email`, `senha`) VALUES ('$nome', '$sobrenome', '$email', '$senha')");
if($insert) {
$codigo = $mysqli->insert_id;
if(empty($_GET['codigo'])) $_GET['codigo'] = $codigo;
echo "<script> alert ('Usuário registrado com sucesso!'); location.href='cadastrou.php' </script>";
} else {
$erro = true;
echo $mysqli->error;
}
} else {
$sql = "UPDATE `usuarios` SET
`nome` = '$nome',
`sobrenome` = '$sobrenome',
`email` = '$email',
`senha` = '$senha'
WHERE
`codigo` = $codigo";
$update = $mysqli->query($sql);
if($update) {
echo "<script> alert ('Usuário atualizado com sucesso!'); location.href='cadastrou.php' </script>";
} else {
$erro = true;
echo $mysqli->error;
}
}
}
} else {
$erro = true;
echo $mysqli->error;
}
if ($erro){
$codigo = '';
$nome = '';
$sobrenome = '';
$email = '';
$senha = '';
$csenha = '';
}
}
if (!empty($_GET['codigo']) && filter_var($_GET['codigo'], FILTER_VALIDATE_INT)){
$select = $mysqli->query("SELECT * FROM usuarios WHERE Email='$email'");
if($select) {
$row = $select->num_rows;
$f = $select->fetch_assoc();
if($row > 0) {
$codigo = $f['codigo'];
$nome = $f['nome'];
$sobrenome = $f['sobrenome'];
$email = $f['email'];
}
}
}
?>
<body>
<form action="" method="POST">
<input type="hidden" name="codigo" value="<?=$codigo?>">
<label><br />
Nome:
</label><br />
<input type="text" name="nome" placeholder="Primeiro Nome" value="<?=$nome?>" />
<label><br />
Sobrenome:
</label><br />
<input type="text" name="sobrenome" placeholder="Segundo Nome" value="<?=$sobrenome?>" />
<label><br />
Email:
</label><br />
<input type="text" name="email" placeholder="[email protected]" value="<?=$email?>" />
<label><br />
Senha:
</label><br />
<input type="password" name="senha" placeholder="********" />
<label><br />
Confirmar Senha:
</label><br />
<input type="password" name="csenha" placeholder="********" /><br /><br />
<input type="submit" value="Registrar" name="button" />
<input type="reset" name="Redefinir" value="editar"/>
</form>
</body>
Considerations
Consider encrypting your password, study on:
- Encrypt password and log in PHP and PDO
- What is the best way to create a PHP login system
Consider using a library to manage your connection:
- https://github.com/KaduAmaral/ConnectionMSi
Consider separating your registration code from the registration page, read more on:
- How to implement the MVC standard in PHP
- Good MVC practice
Thank you for your reply, but my problem has been solved. :)
– Ruan Rodrigues
Tranquil @Ruanrodrigues, thanks for the question.
– KaduAmaral
I didn’t know that
filter_var
and interesting considerations :D– Maicon Carraro
Your answer helped a lot too ^^
– Ruan Rodrigues