Launch Exception with error # 1452 - Can not add or update child row: a foreign key constraint fails

0

I'm developing an application where the user types some information, two of them are CodeMotorist and CodeVeiculo.

This is an excerpt from my code:

try {
        $database->query($sql);

        $_SESSION['message'] = 'Registro cadastrado com sucesso.';
        $_SESSION['type'] = 'success';
    } catch (Exception $e) {

        $_SESSION['message'] = 'Não foi possivel realizar a operação.';
        $_SESSION['type'] = 'danger';
    }

I am able to make the normal registrations, the problem is that when the user informs a Motorist Code or Vehicle Code that does not exist the system does not give Exception (It should give an Exception because these data are Foreign Keys) the system does not do the same insertion, what I need is to adapt this code to give an Exception with the error or change the parameter of the condition, to inform the user that the registration gave an error.

    
asked by anonymous 15.06.2017 / 06:44

2 answers

1

It does not fail because MySqli does not return a Exception in the same way as php.

To catch a Mysqli error, you can create a function and call it if the query gives an error.

    $database->query($sql) or die(erro());//Utilizei erro() como um exemplo de função.

    $_SESSION['message'] = 'Registro cadastrado com sucesso.';
    $_SESSION['type'] = 'success';

Or make a if , since the query will return true if the query succeeded and false if it gave an error: (I recommend this option more)

if($database->query($sql))
{
    $_SESSION['message'] = 'Registro cadastrado com sucesso.';
    $_SESSION['type'] = 'success';
}
else 
{
    $_SESSION['message'] = 'Não foi possivel realizar a operação.';
    $_SESSION['type'] = 'danger';
}
    
15.06.2017 / 15:49
1

Hi, why do not you check first if the fields exist with a select in the correct tables if there is no forward for your error. if row count == 0 because if you exist or bring an object it's all you need to get to the next set of data. you can do a sub function that does this search and returns true or false.

    
15.06.2017 / 15:28