Error UPDATING Duplicate entry '1' for key 'PRIMARY'

1

I'm trying to update a record in the database and I get this error:

<h1>A Database Error Occurred</h1>
<p>Error Number: 1062</p>
<p>Duplicate entry '1' for key 'PRIMARY'</p>
<p>UPDATE 'compra' SET 'compra_id' = '1', 'fecha_compra' = '2018-06-10 00:00:00', 'cantidad' = 29, 'id_tarjeta' = '1', 'cantidad_comprada' = '30'</p>
<p>Filename: C:/xampp/htdocs/GestoAG/system/database/DB_driver.php</p>
<p>Line Number: 691</p>

I'm using CodeIgniter as a framework, and this is my code snippet:

$compra_to_update = $this->get_compra_to_update($ingreso ['id_tarjeta']);
$compra_to_update[0]['cantidad'] = $compra_to_update[0]['cantidad'] - $ingreso['cantidad_tarjetas'];
if (empty ($ingreso_id)) {
            try {
                $this->db->insert(self::TABLE_NAME, $ingreso);
                $this->db->insert_id();
                $this->db->update(self::COMPRA_TABLE, $compra_to_update[0]);
                $re = $this->db->update(self::STADISTIC_TABLE, $historico_array[0]);
                return $re ? "OK" : "F";
            } catch (Exception $ex) {
                return $ex->getMessage();
            }
}

What I do not understand is that if I am doing it in the same way as when updating the STADISTIC_TABLE table (in the code it is), then why do I get that error ??, will it be something in the MySQL database ???

    
asked by Yasiel Espinosa 28.06.2018 в 15:28
source

1 answer

1

Your update

UPDATE 'compra' 
SET 'compra_id' = '1',
    'fecha_compra' = '2018-06-10 00:00:00',
    'cantidad' = 29,
    'id_tarjeta' = '1',
    'cantidad_comprada' = '30'

does not have a WHERE clause, so you are trying to update ALL the rows in the table. Obviously you can not put more than one the same PK.

    
answered by 28.06.2018 / 15:54
source