1
CREATE TABLE users(

  USERID BIGINT AUTO_INCREMENT,
  FNAME  CHAR(50),                        
  LNAME  CHAR(50), 
  EMAIL  CHAR (100),               
  PHONE  CHAR (50),        
  PRIMARY KEY (USER_ID),
  UNIQUE KEY EMAIL (EMAIL),
  UNIQUE KEY PHONE (PHONE)
) ENGINE=InnoDB CHARSET=utf8mb4;


CREATE TABLE items(
  ITEMS_ID       BIGINT AUTO_INCREMENT,                       
  USERID         BIGINT,    
  ITEMS_TO       BIGINT,
  ITEMS_FROM     BIGINT,                     
  ACCEPTED_ITEMS BIGINT,                     
  PRIMARY KEY (ITEMS_ID),
  FOREIGN KEY (USERID) REFERENCES users(USERID),
  FOREIGN KEY (ITEMS_TO) REFERENCES users(USERID),
  FOREIGN KEY (ITEMS_FROM) REFERENCES users(USERID),
  FOREIGN KEY (ACCEPTED_ITEMS) REFERENCES users(USERID)
) ENGINE=InnoDB CHARSET=utf8mb4;

I get this error

DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails (`db701`.`items`, CONSTRAINT `items_ibfk_2` FOREIGN KEY (`ITEMS_TO`) REFERENCES `users` (`USERID`))

when I run this:

$ID = '1';
$NULL = 'NULL';
$ID2 = '2';
$ID3 = '1';

my $update = $DBH->prepare("UPDATE items SET ITEMS_TO =?, ITEMS_FROM =? WHERE USERID =? AND ITEMS_ID = ?");
$update->execute($ID, $NULL, $ID2, $ID3);
$update->finish();

It works without ITEMS_FROM and I want to set ITEMS_FROM to null.

This works:

my $update = $DBH->prepare("UPDATE items SET ITEMS_TO =? WHERE USERID =? AND ITEMS_ID = ?");
$update->execute($ID, $ID2, $ID3);
$update->finish();  
2
  • I think you've got a couple of stray + signs in your question, but I can't be certain. (There's one in for +eign, for instance, as well as several in the code which follows that.) Please edit your question to remove the ones that don't belong. Commented Oct 25, 2018 at 21:57
  • Cross-posted at perlmonks.org/?node_id=1224662 Commented Nov 1, 2018 at 15:12

1 Answer 1

6

You shouldn't put NULL in quotes. That's trying to set ITEMS_TO to the literal string 'NULL', not a null value. MySQL will then try to convert this to a BIGINT; since it doesn't look like a number it will be converted to 0. Since there's no user_id = 0 in the users table, the foreign key check fails.

You should use the Perl value undef to represent the SQL null value:

$NULL = undef;

See Which one represents null? undef or empty string

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.