goldiman
goldiman

Reputation: 187

Cannot add or update a child row: a foreign key constraint fails

SQLSTATE[23000]: Integrity constraint violation: 1452

Cannot add or update a child row: a foreign key constraint fails

(whnkepbk_Hland.interests, CONSTRAINT interests_ibfk_3 FOREIGN KEY (scale_id) REFERENCES scales_reference (scale_id))

I know that the problem is because I have to set value to scale_id to add this data line.

And I do it :

    $requete = "INSERT INTO interests (onetsoc_code,element_id,scale_id,data_value) VALUES (:onetsoc_code,:element_id,:scale_id,:data_value)"; 
...           
$InsertMetier->bindParam(':scale_id', $scale);
            var_dump($scale);
            var_dump($InsertMetier);
            $InsertMetier->execute();

Here the content of the var_dump :

</pre>Ol<pre class='xdebug-var-dump' dir='ltr'><small>string</small> <font color='#cc0000'>'Ol'</font> 

'INSERT INTO interests (onetsoc_code,element_id,scale_id,data_value) VALUES (:onetsoc_code,:element_id,:scale_id,:data_value)'

My scale variable do have a value according to the var_dump and my query sounds legitimate.

Here a screenshot of my database (interest) :

enter image description here

scales_reference:

enter image description here

Structure of interest :

enter image description here

Structure of scale_reference :

enter image description here

If someone has any idea what I have done wrong.

Upvotes: 1

Views: 163

Answers (2)

goldiman
goldiman

Reputation: 187

What's the difference between Ol and OI you can't even see it on stackoverflow , how about "oi" and "ol", yes there is a big difference and I was not putting "OI" but I was putting OL so that was the issue.

Upvotes: 0

Marki555
Marki555

Reputation: 6860

MySQL error Integrity constraint violation: 1452 from MySQL manual:

For storage engines supporting foreign keys, MySQL rejects any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table.

That means you are either:

  1. Inserting into your interest table with scale_id value, which doesn't exist in the parent table (scale_reference).
  2. Having error in your query and inserting empty scale_id - from the code snippet it is not clear how you are replacing all placeholders (:xx) with actual values from PHP variables and we don't see the actual query as it is sent to the MySQL server.

You can try to run the desired query directly on MySQL without PHP. If it works, then you have issue in your PHP code.

Upvotes: 1

Related Questions