View and edit registered data

Asked

Viewed 6,350 times

3

I created a registration system and wanted to know how I do so that the information that was registered is displayed on the page and that the user can edit them. Follow my code below.

<body>
<form action="" method="POST">
<label><br />
    Nome:
</label><br />
    <input type="text" name="nome" placeholder="Primeiro Nome" />
<label><br />
    Sobrenome:
</label><br />
    <input type="text" name="sobrenome" placeholder="Segundo Nome" />
<label><br />
    Email:
</label><br />
    <input type="text" name="email" placeholder="[email protected]" />
<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="resetar"/>
        </form>
    </body>
</html>

<?php
    if(isset($_POST["button"])) {
        $nome       = $_POST["nome"];
        $sobrenome  = $_POST["sobrenome"];
        $email      = $_POST["email"];
        $senha      = $_POST["senha"];
        $csenha     = $_POST["csenha"];

        if($nome == "" || $sobrenome == "" || $email == "" || $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;
        }   

        $select = $mysqli->query("SELECT * FROM usuarios WHERE Email='$email'");
        if($select) {
        $row = $select->num_rows;
        if($row > 0) {
            echo "<script> alert ('Já existe um usuário com esse e-mail'); </script>";
        } else {
            $insert = $mysqli->query("INSERT INTO `usuarios`(`nome`, `sobrenome`, `email`, `senha`) VALUES ('$nome', '$sobrenome', '$email', '$senha')");
        if($insert) {
            echo "<script> alert ('Usuário registrado com sucesso!'); location.href='cadastrou.php' </script>";
        }   else {
                echo $mysqli->error;
            }   
        }
    }   else{
    echo $mysqli->error;

    }   

}       
?>

2 answers

4

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:

  1. Encrypt password and log in PHP and PDO
  2. What is the best way to create a PHP login system

Consider using a library to manage your connection:

  1. https://github.com/KaduAmaral/ConnectionMSi

Consider separating your registration code from the registration page, read more on:

  1. How to implement the MVC standard in PHP
  2. Good MVC practice
  • Thank you for your reply, but my problem has been solved. :)

  • 2

    Tranquil @Ruanrodrigues, thanks for the question.

  • 2

    I didn’t know that filter_var and interesting considerations :D

  • Your answer helped a lot too ^^

3


Based on their SELECT you can see that you use the field email as identifier of each user, then its UPDATE will look a lot like the INSERT and the only detail is WHERE email = $email.

if($row > 0) {
    $update = $mysqli->query("UPDATE `usuarios` 
                              SET `nome` = '$nome', 
                                  `sobrenome` = '$sobrenome',
                                  `senha` = $senha
                              WHERE `email` = $email");
} else {
    $insert = $mysqli->query("INSERT INTO `usuarios`(`nome`, `sobrenome`, `email`, `senha`) VALUES ('$nome', '$sobrenome', '$email', '$senha')");
if($insert) {
    echo "<script> alert ('Usuário registrado com sucesso!'); location.href='cadastrou.php' </script>";
} elseif ($update) {
    cho "<script> alert ('Usuário atualizado com sucesso!'); location.href='atualizou.php' </script>";
} else {
    echo $mysqli->error;
}

Only this code has 2 big problems:

  1. The concatenation of parameters in the query causes security flaws, an example of this, is that it will allow any user to run a SQL Injection.
  2. Your screen does not validate the user, if any user other than the administrador enter this screen it can change the password of any user.

Solution of problem #1

Pass parameters through the bind_param.

$sql = "UPDATE `usuarios` 
        SET `nome` = ?, 
            `sobrenome` = ?,
            `senha` = ?
         WHERE `email` = ?";


$stmt = $conn->prepare($sql);

/* s = string, i = integer, d = double,  b = blob */
$stmt->bind_param('ssss', $nome, $sobrenome, $senha, $email);

$stmt->execute();

if (!$stmt->errno)
    echo 'Atualizado {$stmt->affected_rows} registros';

-

Solution of problem #2

In the same way that you validate the fields whether they are filled in or not, you could validate whether the logged in user $_SESSION is a user who has these privileges.

  • Thank you very much, it helped a lot ! I have marked as certain

Browser other questions tagged

You are not signed in. Login or sign up in order to post.