Launch Exception with error #1452 - Cannot add or update a Child Row: a Foreign key Constraint fails

Asked

Viewed 109 times

0

I am developing an application where the user type some information, two of them are Code Driver and Code.

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 managing to do the normal registrations, the problem is that when the user informs a Code driver or Code that there is no system does not give a Exception (Should give a Exception because these data are Foreign Keys) the system does not even insert, 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 error.

2 answers

0

Hi, why don’t you check first if the fields exist with a select in the correct tables if there is no forwarding to your error. if Row Count == 0 why whether to exist or bring an object is all you need to make it go to the next dataset. Voce can make a subfunction that does this search and returns true or false.

0


He doesn’t make mistakes because the MySqli does not return a Exception in the same way as php.

To capture an error from Mysqli, you can create a function and call it if the query gives 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 has worked, and false in case of error: (I recommend this option)

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';
}
  • I used your 2 example, thank you very much for the past knowledge for me.

Browser other questions tagged

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