CRUD PHP No update, no error

Asked

Viewed 774 times

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 on the button it does not return any error, only returns to the page index1.php, as I commanded in the header. But in the bank the "changed" field remains the same, as if it had not made any changes.

Could someone help me? Grateful!

  • Where are you initiating the variable $id in the part that makes the UPDATE?

  • in the first code you posted, echo the $sql variable and see what it returns. just to make sure she’s getting the variables correctly.

  • I put the command to capture the id... But it continues the same way :/ I did an echo on the $sql variable like I said, and returned it here: UPDATE users SET name = :name, nasc = :nasc, email = :email, password = :password WHERE id = :id

1 answer

5


In this block you link 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);

However, at the time of capture, you are picking up all the fields except the $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);

Also, you need to put the value on the form:

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

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 doesn’t have access.

If the user can only change the data itself, he can remove the hidden field and use only the ID of who is logged in, but anyway, probably need to validate the fields more carefully.

  • I put the command to capture the id... But it remains the same :/

  • Not just capture it, you need to put it in the form, test it, and see if it’s being sent. For example, after the mentioned changes, you need to look at the form source in the browser and see if it was the right ID in the form.

  • 1

    When I entered the id capture command, I entered it wrong, I wrote $POST instead of $_POST... I typed it without the underline. Now you solved the problem. At first the problem was the missing id capture. Thanks for the @Bacco help

  • @Gabriel we are here for this, I’m glad you solved.

Browser other questions tagged

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