CRUD PHP Do not update and give no error

3

I'm having problems when I try to run an UPDATE on my system in PHP + MySQL.

I have the file code edit:

<?php

require_once 'init.php';

// resgata os valores do formulario
$nome = isset($_POST['nome']) ? $_POST['nome']: null;
$nascimento = isset($_POST['nascimento']) ? $_POST['nascimento']: null;
$email = isset($_POST['email']) ? $_POST['email']: null;
$senha = isset($_POST['senha']) ? $_POST['senha']: null;
$seg_senha = password_hash($senha, PASSWORD_DEFAULT);

// Validação para evitar dados vazios
if (empty($nome) || empty($nascimento) || empty($email) || empty($senha)) {
    echo 'Volte e preencha todos os campos.';
    exit;
}

// Atualiza o banco
$pdo = db_connect();
$sql = "UPDATE usuarios SET nome = :nome, nasc = :nasc, email = :email, senha = :senha WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':nome', $nome);
$stmt->bindParam(':nasc', $nascimento);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':senha', $seg_senha);
$stmt->bindParam(':id', $id);

if ($stmt->execute()){
    header('Location: ../index1.php');
}else{
    echo 'Erro ao atualizar usuario.';
    print_r($stmt->errorInfo());
}

Now the file with form for user editing:

<?php

require_once 'core/init.php';

// Pega o id da URL
$id = isset($_GET['id']) ? (int)$_GET['id']: null;

// Valida o id
if (empty($id)) {
    echo 'ID para alteração nao definido';
    exit;
}

// Busca os dados do usuario a ser editado
$pdo = db_connect();
$sql = "SELECT nome, nasc, email, senha FROM usuarios WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

$stmt->execute();

$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Se o método fetch() não retornar um array, significa que o ID não corresponde a um usuário válido
if(!is_array($user)){
    echo 'Nenhum usuario encontrado.';
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<!-- ==================== TABLE INICIO - BOOTSTRAP ==================== -->
<div class="panel panel-success " style="width: 60%; margin: 0 auto; padding: 20px">
        <div class="panel-heading">
            <center>
                <b>EDITAR USUARIO</b>
            </center>
        </div>

        <div class="panel-body">

            <form method="POST" action="core/editar.php">
                <div class="form-group">
                     <input type="hidden" value="" name="id" class="form-control" id="exampleInputId1"></a>
                </div>
                <div class="form-group">
                    <label for="nome">Nome</label>
                     <input type="text" value="<?php echo $user['nome'] ?>" name="nome" class="form-control" id="nome" placeholder="Nome"></a>
                </div>

                <div class="form-group">
                    <span class="label label-default">Data de nascimento</span>
                    <input type="date" value="<?php echo $user['nasc'] ?>" data-date="" data-date-format="DD MMMM YYYY" class="form-control" for="nasc" name="nascimento">
                </div>

                <div class="form-group">
                    <label for="email">E-MAIL</label>
                    <input type="email" value="<?php echo $user['email'] ?>" name="email" class="form-control" id="email" placeholder="E-MAIL">
                </div>

                <div class="form-group">
                    <label for="senha">Senha</label>
                    <input type="password" value="<?php echo $user['senha'] ?>" name="senha" class="form-control" id="senha" placeholder="Senha">
                </div>

                <input type="hidden" name="id" value="<?php echo $id ?>">

            <button type="submit" class="btn btn-default">Finalizar edição</button>
            </form>
        </div>
    </div>
<!-- ==================== TABLE INICIO - BOOTSTRAP ==================== -->
</body>
</html>

When I change the fields and click the button it does not return any error, it only returns to page index1.php , as I sent in header . But in the bank the "changed" field remains the same, as if it had not made any changes.

Could anyone help me? Thanks!

    
asked by anonymous 02.01.2017 / 22:34

1 answer

5

In this block you bind the variable $id to use in WHERE

$stmt->bindParam(':nome', $nome);
$stmt->bindParam(':nasc', $nascimento);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':senha', $seg_senha);
$stmt->bindParam(':id', $id);

At the time of capture, however, you are catching all fields, minus $id :

// resgata os valores do formulario
$nome = isset($_POST['nome']) ? $_POST['nome']: null;
$nascimento = isset($_POST['nascimento']) ? $_POST['nascimento']: null;
$email = isset($_POST['email']) ? $_POST['email']: null;
$senha = isset($_POST['senha']) ? $_POST['senha']: null;
$seg_senha = password_hash($senha, PASSWORD_DEFAULT);

In addition, you need to value in the form:

<input type="hidden" value="<?php echo $user['id']; ?>" name="id" class="form....
                             ^^  falta algo assim  ^^

By solving these things, you have to think of a way for a malicious user not to manually change the ID and change an account that does not have access.

If the user can only change his own data, he can remove the hidden field and use only the id of who is logged in, but in any case, he probably needs to validate the fields more carefully.     

02.01.2017 / 22:43