$mysqli query fails, foreign key constraint fails - php

This insert command fails:
INSERT INTO posts (id, headline, content, post_date, blog) VALUES (default, 'Birds
in Nepal are being Messed With', 'Have you heard about this? There are birds in
the country of Nepal that are sitting around minding their own business, when out
of nowhere they are getting messed with. Messed with!', curdate(), 'cost');
It dies with this error message:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint
fails (`allanwebdev`.`posts`, CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`blog`)
REFERENCES `blogs` (`blog`))
There are two tables, one called 'blogs' and one called 'posts'.
'blogs' has one column called 'blog' which serves as a primary key:
DESCRIBE BLOGS;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| blog | varchar(10) | NO | PRI | | |
+-------+-------------+------+-----+---------+-------+
SELECT * FROM BLOGS;
+----------+
| blog |
+----------+
| code |
| politics |
| satire |
+----------+
'posts' has a foreign key column called 'blog' which references the primary key in 'blogs'.
DESCRIBE POSTS;
+-----------+----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+----------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| headline | varchar(60) | YES | | NULL | |
| post_date | date | YES | | NULL | |
| content | varchar(64000) | YES | | NULL | |
| blog | varchar(10) | YES | MUL | NULL | |
+-----------+----------------+------+-----+---------+----------------+
What. The heck. Am I doing wrong? Many thanks. This error message does exist elsewhere but invariably they are more complex problems. I'm operating simply and directly from a mysql command line.
Note that the sql call is being made from a php mqsqli object $db->query($sql). The actual string doesn't include a semi-colon at the end.

Related

Cannot add or update a child row: a foreign key constraint fails - but I can see that the value does exist

I am using the codeigniter4 framework. I have a database called taskapp. The db has 2 tables as follows;
table: user
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | | |
| email | varchar(60) | NO | | | |
+----------+-------------+------+-----+---------+----------------+
and this is my other table
table: post
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| post_id | int(11) | NO | PRI | NULL | auto_increment |
| post_user_id | int(11) | NO | | | |
| post | varchar(60) | NO | | | |
+----------+-------------+------+-----+---------+----------------+
When I update the post table (eg change post), I get the following error:
Cannot add or update a child row: a foreign key constraint fails (`taskapp`.`post`,
CONSTRAINT `post_ibfk_1` FOREIGN KEY (`post_user_id`)
REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
I checked table and field collation and both are the same.
I understand from reading other posts that essentially I am trying to update post table that doesn't have corresponding reference in user table. The post_user_id is 58 and in the user table I see 58.
For now, I am working on update of text ('post'). Next I want to change the post_user_id to another id in the user table.
Any guidance appreciated.

Speed up inserting IDs from one large mysql table to another

I can achieve what I want to do it's just terribly slow and I'm pretty sure there is a better way. Here is an abstract:
I have two tables I imported from two text files (via LOAD DATA INFILE). There is no primary and foreign key relationship between these tables yet.
Table 1 - Events: 1.5 millions rows (person_id values are empty)
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| event_id | int(11) | NO | PRI | NULL | auto_increment |
| person_id | int(11) | NO | UNI | NULL | |
| event_details| longtext | NO | | NULL | |
| person_name | varchar(30) | NO | | NULL | |
| mother_name | varchar(30) | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
Table 2 - People: 140 000 rows
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| person_id | int(11) | NO | PRI | NULL | auto_increment |
| person_name | varchar(30) | NO | | NULL | |
| mother_name | varchar(30) | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
I'm trying to insert the person_id from the people table into the events table.
I've tried a few methods, basically loop through each row of the events table find the person_id in the people table using the person_name and mother_name in the current row from the events table. Then insert the person_id into the events table.
My current query takes a bout 5 days to update all 1.5 million rows in the events table. How can I make this faster?
I'm using laravel and php but any suggestions welcome.

Mysql speed: table with many columns or 2 tables using a join

I tried searching for this but I could not find anything about this but design choices.
So my question is like the title. What is faster? Create 1 table with many columns or create 2 or 3 (for many to many) tables with join(s).
I like the idea of have multiple tables so the data is separated. Mostly for many to many like data. But my friend told me having 5 columns with boolean is just fine. But I like the idea of have a table with the settings and then a table between with user.id and setting.id. But my question is also, does it have a impact on the query?
example:
Users
- id
- Email
- SettingA
- SettingB
- SettingC
OR example:
Uers
- id
- email
Users_Settings
- user_id
- setting_id
Settings
- id
- someSettingsValue
What woult be faster for Mysql to query the data? (retrieving settings for user)
not at all.. Only joins between 2 r 3 will take time compared to single table fields.
It's not about preferring single table with many columns or preferring multiple tables. It's about Normalization.
According to your provided schema, if all users will always have three settings, i.e. Setting A, B and C, then it's better to create single table with these three columns for settings.
users table:
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| Email | varchar(128) | NO | | NULL | |
| SettingA | tinyint(1) | NO | | NULL | |
| SettingB | tinyint(1) | NO | | NULL | |
| SettingC | tinyint(1) | NO | | NULL | |
+----------+--------------+------+-----+---------+----------------+
But if any of the setting is saved is null, then better is to create separate table for settings and then a pivot table for maintaining users' settings without primary key.
users table:
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| Email | varchar(128) | NO | | NULL | |
+-------+--------------+------+-----+---------+----------------+
settings table:
+---------------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| setting_value | tinyint(1) | NO | | NULL | |
+---------------+------------+------+-----+---------+----------------+
setting_user pivot table:
+------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| setting_id | int(11) | NO | | NULL | |
| user_id | int(11) | NO | | NULL | |
+------------+---------+------+-----+---------+-------+
Where setting_user is the pivot table.
One more thing is considered when creating schema, that, will there be always three settings, or will there be more in future, when application is expanded!

Can't solve child parent association in cakephp 3

I have table with a parent child relationship with itself:
mysql> desc features;
+---------------------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+-------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| featureID | varchar(45) | NO | | NULL | |
| probeID | int(11) | YES | | NULL | |
| shortName | varchar(45) | NO | | NA | |
| start | int(11) | NO | | NULL | |
| stop | int(11) | NO | | NULL | |
| strand | int(11) | NO | | NULL | |
| curatedManually | varchar(45) | NO | | NA | |
| created | timestamp | NO | | CURRENT_TIMESTAMP | |
| descriptions_id | int(11) | YES | MUL | NULL | |
| features_types_id | int(11) | NO | MUL | NULL | |
| chromosomes_id | int(11) | NO | MUL | NULL | |
| species_id | int(11) | NO | MUL | NULL | |
| strains_id | int(11) | NO | MUL | NULL | |
| parents_features_id | int(11) | YES | MUL | NULL | |
+---------------------+-------------+------+-----+-------------------+----------------+
The according fields are parents_features_id and id, because a feature can have "child"-features or "parent"-features. There is a foreign key relationship established with this fields.
KEY `fk_features_Features1_idx` (`parents_features_id`),
CONSTRAINT `fk_features_Features1` FOREIGN KEY (`parents_features_id`) REFERENCES `features` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
I used "cake bake all features" to create all necessary models, controllers etc.
When I open the features page I only get the error message "Features is not associated with ParentsFeatures"
I tried to solve it by exchanging the automatic original code
$this->belongsTo('Features', [
'foreignKey' => 'parents_features_id'
in Model/Table/FeaturesTable.php for this relationship by the following code:
$this->belongsTo('ParentsFeatures', [
'className' => 'Features',
'foreignKey' => 'parents_features_id'
]);
$this->hasMany('ChildFeatures', [
'className' => 'Features',
'foreignKey' => 'parents_features_id'
But than I get the error message "Features is not associated with Features"
I am a little bit stuck here and would really appreciate any help to solve this.
all the best
Nadine
Making changes to the associations in your table will not change the way the baked controllers will query the data, you'll have to change them too, or re-bake your code.
However, this will never bake correctly unless you start following the conventions, that is name the foreign key column parent_id, only then bake will be able to create the proper associations (which will be named ParentFeatures and ChildFeatures), and while you're at it, consider changing the other column names too (lowercase underscored).
That being said, there might be a bug that occours somewhere between renaming indexes, creating and deleting foreign key constraints, etc (can't pinpoint it down), which then causes wrong association names used for contain in the find() calls of the controller actions, ie bake will generate something like
'contain' => ['Features']
instead of
'contain' => ['ParentFeatures']
which it used for the association in the baked table class.
However I'm not being able to reproduce it reliably right now. In case this is what you are experiencing, you might want to report this as an issue over at GitHub.
In case re-baking doesn't fix it, manually check the find() calls in your controller actions and change the contained association to ParentFeatures.

Cannot add or update a child row: a foreign key constraint fails(Foreign key issue in mysql)

I am getting this error whenever I try to Insert Data into my "Student" table.
Below are the two tables, I am using MySql :
student table:
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+-------------------+----------------+
| S_id | int(20) | NO | PRI | NULL | auto_increment |
| U_id | int(11) | YES | MUL | NULL | |
| sname | varchar(20) | YES | | NULL | |
| gender | varchar(20) | YES | | NULL | |
| email | varchar(320) | YES | UNI | NULL | |
| Phone_Number | int(20) | YES | | NULL | |
user table:
Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+-------------------+----------------+
| U_id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | NO | | NULL | |
| password | varchar(20) | NO | | NULL | |
| email | varchar(255) | NO | UNI | NULL | |
When I try to run this query ,
INSERT INTO student(U_id,sname,gender,email,Phone_Number) VALUES ('$U_id','$sname','$gender','$email','$Phone_Number');
I am getting this error:
Cannot add or update a child row: a foreign key constraint fails (`Learn`.`student`, CONSTRAINT `student_ibfk_1` FOREIGN KEY (`U_id`) REFERENCES `user` (`U_id`))
I tried to look for the solution but most of them are saying keep a common Engine like InnoDB on both the tables but in my table its already defined.I have even followed the steps given here https://stackoverflow.com/a/9139206/2545197
but nothing worked for me.
I made an SQL Fiddle and everything works perferctly.
The only way I can reproduce the error is when a row is inserted into student before the corresponding row in user exists. Can you please double check that this is really true for each inserted row.
Also, you should var_dump() your PHP variables used for the INSERT and check if the problem lies there. IMHO, it can only have to do with a non-existing record in the user table.

Categories