How to perform UPDATE with PDO in PHP?


So folks, I wanted to redeem the data to edit in update.php , but how much lost here, how to give a force?

   <div class="container">
<div class="table-responsive">
    <table class="table">
            <?php foreach ($resultado as $key) :?>
            <td><?php echo $key->nome;?></td>
            <td><?php echo $key->marca;?></td>
            <td><?php echo $key->modelo;?></td>
            <td><?php echo $key->quantidade;?></td>
            <td><?php echo $key->estado;?></td>
                <a href="mysql/update.php?id=<?php echo $key->id; ?>">Alterar</a>
                <a href="mysql/delete.php?id=<?php echo $key->id; ?>">/Deletar</a>
        <?php endforeach;?>

  • update.php

        $id = $_GET['id'];
        $sql = $pdo->prepare("UPDATE FROM estoqueprodutos . produtos WHERE id = $id");
        echo $sql->rowCount();
    }catch (PDOException $e){
        echo 'Error: '. $e->getMessage();
    }    ?>


I have a problem, I created this code to be leaner but it is not running and it is not giving me any errors could you help me to solve this problem?         

    try {
        $sql = "update produtos set nome = ?, marca = ?, modelo = ?, quantidade = ?, estado = ? where id = ?";

        $statement = $pdo->prepare($sql);

        $statement->bindParam(1, $_POST['nome']);
        $statement->bindParam(2, $_POST['marca']);
        $statement->bindParam(3, $_POST['modelo']);
        $statement->bindParam(4, $_POST['quant']);
        $statement->bindParam(5, $_POST['estado']);
        $statement->bindParam(6, $_POST['id']);


    } catch (PDOException $e) {
        print $e->getMessage();
} else {
    echo "Desculpe-nos, mas não foi possível alterar este produto. Entre em contato com o suporte!";

? >

asked by anonymous 10.12.2015 / 17:35

1 answer


The logic to perform the update is as follows, in its file update.php it will not execute a UPDATE tabela SET campo = valor .

update.php in you need to query the database through the id received by get, with the information in hand create the html form and fill in the value attribute with the database value something like:

//linhas omitidas ...
$registro = $sql->fetch(PDO::FETCH_ASSOC);

<form method="post" action="gravar.php">
  <input type="hidden" name="id" value="<php echo $registro['id']; ?>" />
  <input type="text" name="nome" value="<php echo $registro['nome']; ?>" />

In the grava.php file, a new or updated record will be saved. But how do you know which operation to perform?

This can be done by checking the value of id (see form fields).


      //realizar um update
      //Não existe um id, logo é um registro novo, insert nele!
10.12.2015 / 17:54