View and edit registered data

3

I created a registration system and wanted to know how to make the information that was registered appear on the page and that the user can edit it. 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;

    }   

}       
?>
    
asked by anonymous 11.06.2015 / 13:15

2 answers

3

Based on your SELECT to see that you use the email field as the identifier for each user, then your UPDATE will be very similar to 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;
}

But this code has 2 major issues :

  • Concatenation of parameters in query causes security flaws, an example of this is that it will allow any user to perform a SQL Injection .
  • Your screen does not validate the user, if any user other than administrador enters this screen he can change the password of any user.
  • Problem # 1 Solution

    Pass the parameters through 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';
    

    -

    Problem # 2 Solution

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

        
    11.06.2015 / 13:58
    4

    How to do

    To enable editing you need a variable to select the user and leave the data in the form. First of all, get all your PHP code and put it before the HTML code.

    Now start the variables that go in Form HTML :

    $codigo = '';
    $nome = '';
    $sobrenome = '';
    $email = '';
    

    Enter a field for the user code in the form

    <input type="hidden" name="codigo" value="<?=$codigo?>">
    

    Do not forget to pass the remaining variables in the value attributes of the other fields.

    Get this field on POST :

    $codigo     = filter_var($_POST["codigo"], FILTER_VALIDATE_INT);
    

    Now when we check if there is a user in the database, we also need to check if it is a new one or edit, 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 of insert, we need to check if it is new or update, if it is new to get 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 lastly, generate 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 about in:

  • Encrypt password and log in to PHP and PDO
  • What is the best way to create a login system with PHP
  • Consider using a library to manage your connection:

  • link
  • Consider separating your registration code from the registration page, read more at:

  • Implementing the MVC standard in PHP
  • Good MVC Practices
  • 11.06.2015 / 14:01