S
S
Steve2021-07-20 09:45:33
PHP
Steve, 2021-07-20 09:45:33

Error with foreign key?

I have an error

insert or update on table \"email\" violates foreign key constraint \"email_contact_id_fkey\"\nDETAIL:  Key (contact_id)=(166) is not present in table \"contact\"

There is no contact with id 166 in the contact table.
Is it possible to throw an exception in PHP instead of this error?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lander, 2021-07-20
@usdglander

Well, catch it and process it as you like. Through try...catch.

S
Slava Rozhnev, 2021-07-20
@rozhnev

In development of Lander's answer

<?php
function saveEmail($contactId, $email){
  global $pdo;
  try {
    $stmt = $pdo->prepare("
      INSERT INTO emails(contact_id, email) 
      VALUES (:contact_id, :email)");
    $stmt-> bindValue(':contact_id', $contactId);
    $stmt-> bindValue(':email', $email);
    return $stmt-> execute();
  } catch (PDOException $Exception ) {
    print_r($Exception);
    return false;
  }
}

saveEmail(166, '[email protected]');

Test PHP & SQL code online

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question