Excepcion primary key in php and mysql

0

I'm inserting data from a txt in a base and it turns out that a field that is the primary key is sometimes repeated, I need to generate a "report" that at the time that file is uploaded, it notifies that primary keys were repeated to the user Is there a way to insert data that does not repeat itself and put an exception for those who do? thanks

    
asked by sanlegas 09.04.2018 в 07:26
source

1 answer

1

Perfectly, in the php what you can do is, take each primary key field and make a select to see if it already exists, if there is notification to the user, if you do not exist, you make an insert.

METHOD 1

<?php
    //Con cada linea del txt, lo ideal es hacer un array nominativo
    $linea = array("id" => 1, "texto" => "test", "otro" => "blabla");

    //Ejemplo con mysqli orientado a objetos
    $result = $mysqli->query("SELECT * FROM tabla WHERE id = " . $linea['id'];
    if($result->num_rows > 0){
        //Si es mayor que 0, hay algun campo repetido, lo notificas al usuario
    }else{
        //Si no, no esta repetido y se peude hacer un insert
    }

I hope it has been understood, it is the fastest and easiest way, but it is reliable.

METHOD 2

You can use a try catch to capture the errors.

try {
    // Ejecutas aqui tu insert con normalidad
} catch(Exception $e) {
    // Capturas todos los errores
}

Do a var_dump of each error $ e that you get out because you will get errors of duplicates and errors of connection among others, you should make a filter to know if it has not been inserted by duplicity or for other reasons, you should leave a error like this:

Error 1062 inserting row ID 1: Duplicate entry '1' for key 'PRIMARY'

If the id of the error is 1062, it means that it is duplicated and you notify the user.

    
answered by 09.04.2018 в 07:47