I have this mysql query (which add values from a form into a table upon submission). It returns an error message:
$query = "INSERT INTO customers(customerNumber, customerName, contactLastName, contactFirstName, phone, addressLine1, addressLine2, city, state, postalCode, country, salesRepEmployeeNumber, creditLimit) VALUES ('$customer_number', '$customer_name', '$last_name', '$first_name', '$phone_number', '$address_1', '$address_2', '$city', '$state', '$postal_code', '$country', '$sales_number', '$credit_limit')";
$result = mysqli_query($dbc, $query)
or die(mysqli_error($dbc));
ERROR MESSAGE:
Cannot add or update a child row: a foreign key constraint fails (ikb2014_employees.customers, CONSTRAINT customers_ibfk_1 FOREIGN KEY (salesRepEmployeeNumber) REFERENCES employees (employeeNumber))
I am having a hard time deciphering where the 'foreign key constraint' fails. How can I change the the options in the database for the specific table to that I am able so run the query?
This is what the options in the phpMyAdmin show for the table employees and the column employeeNumber (assuming that is where the error is being caused).
# Name Type Collation Attributes Null Default Extra Action
1 employeeNumber int(11) No None AUTO_INCREMENT
I have not worked with a database before so it is hard for me to understand where and why the issue occurs. Any input on how to fix the constraint to properly run the query would be appreciated.
A failure of a foreign key constaint means that you are trying to enter data into a column of one table that does not exist in another table. The foreign key constraint is put in place to ensure that the data you insert into the child table exists in the parent table.
In your case, you're attempting to insert (or not attempting to insert) data in to the salesRepEmployeeNumber column of the customers table. In order to successfully do so, you need to ensure that the value that is provided for salesRepEmployeeNumber exists in the employeeNumber column of the employees table.
The foreign key constraint error is objecting to the value being assigned to the salesRepEmployeeNumber column. The foreign key constraint is checking that the value supplied for that column matches a row in employees table, it;s looking for a row that has the same value for employeeNumber, and it's not finding one.
If you don't want the database to enforce a foreign key constraint, then don't define one.
If you do want the constraint, then that's saying that you have to supply either a valid employeeNumber or a NULL value for salesRepEmployeeNumber.
From the code we're seeing, it looks like the SQL statement is vulnerable to SQL Injection. (We're not seeing any guarantees about the values of the variables being incorporated into the SQL text. If any of those values is potentially unsafe, then those values need to be properly escaped, for example, using mysqli_real_escape_string function.
A better pattern is to use a prepared statement with bind placeholders.
If your foreign key is wrong, you can easily remove it in phpMyAdmin.
Go to the customers table, click on 'structure' tab and at the bottom there will be an +Indexes hidden list, expand it and click DROP on the selected index.
Related
I have a table(APPOINTMENT) with 3 foreign keys.
These are Staff_ID, Dentist_ID, and Patient_ID.
When using the GUI INSERT function I noted only the patient_ID field has a drop down for the patients with the patient table.
However the Staff_ID and Dentist_ID the user can enter any value.
Should all foreign key fields not have a drop down for existing entries in respective tables?
EDIT- adding additional images
When I tried to add the FK again I noted the following error which for some reason I had not noted previously:
MySQL error 1452 - Cannot add or update a child row: a foreign key
constraint fails
The issue in my case was the field I was converting to a FK already had a value in it that had no corresponding value in the primary key column it referencing. There is a good explanation of the error here
Here is my SQL:
INSERT INTO film (film_id, title, description, release_year, language_id, original_language_id,
rental_duration, rental_rate, length, replacement_cost, rating, special_features, last_update)
VALUES ('1001','1 st Grade FBI Agent','An undercover FBI agent must pretend to be
a 1st grade teacher to catch the bad guy', '2014','2','null', '5', '4.99', '123', '2014',
'20.99', 'PG-13', 'Tailers');
Here is the error I get when I run it. This is a preset database I'm using for an assignment for a class, and I was told to insert a new row into the film table.
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (sakila.film, CONSTRAINT fk_film_language_original FOREIGN KEY (original_language_id) REFERENCES language (language_id) ON UPDATE CASCADE)
The value for original_language_id must match the value of language_id for one row in the language table. This requirement is due to a foreign key on the film table.
If this value is an integer it should not be surrounded by quotes.
Your SQL Statement is trying to INSERT 'null' value for the original_language_id field in the film table.
It looks like this original_language_id is a FOREIGN KEY that references the language_id in the language table and is likely the PRIMARY KEY on that table.
Looks like you are giving 'null' as value for original_language_id. Check, whether you have null as value in your language table. If you want to insert value null .... write it just null not 'null'.
It seems that "original_language_id" is a foreign key from the "language" table and the value which you are trying to insert i.e 'null' in this case is not in the parent table(language).
I'm seeing a few problems in your statement. But to answer the question that was asked, look at the "language" table. The value you put in original_language_id must be one of the values in the language.language_id column (or null, see below).
As for the other stuff, several users have already commented on the null value. null is a keyword and should not be in quotes.
ALso, your last 4 values seem to be in a different order than the field list.
I am trying to insert two records to my database at the same time. One with the primary key and the other with the foreign key. However, I get the following error when I try implementing this:
Cannot add or update a child row: a foreign key constraint fails ....(database details).
I have used this query to create the foreign key:
ALTER TABLE `notes` ADD CONSTRAINT `notes_author_fk`
FOREIGN KEY (`authorid`) REFERENCES `audiofeed`.`author`(`authorid`) ON DELETE NO ACTION ON UPDATE CASCADE;
The error statement points at:
$query1 = "INSERT INTO notes(notename,categoryname,file,authorname)";
$query1 .= "VALUES ('$Trackname','$category','$name','$author')";
If the error does in fact occur during the insert statement that you posted, I notice that you are not inserting any value for the authorid column, which is the column that has a foreign key defined.
Normally, this should be ok, as it should simply insert NULL, and that would not violate the foreign key constraint.
However, if the authorid column in the notes table has a default value specification, it may be trying to insert an invalid default value that cannot be found in the author table, thus giving you the error.
You may want to verify how the authorid column is defined, and adjust it as necessary.
Or, make sure you set an appropriate value for authorid in your insert statement.
I´m creating a database addrees and I want to know what I need to set in Mysql to don´t store repeat values?
Like
Addrees 1 ("teste",1,new york,eua);
Addrees 2 ("teste",1,new york,eua);
If this happen my database will not store.
So what I need to do?
To alter an already existing table, run this MySQL command:
alter table yourtablename add unique index(firstcolumn, secondcolumn, thirdcolumn, fourthcolumn);
That'll add the unique constraint to the specified columns. Here's how to specify such a constraint in the CREATE TABLE.
CREATE TABLE buyers (
buyer_id INT UNSIGNED NOT NULL,
first_name CHAR(19) NOT NULL,
last_name CHAR(19) NOT NULL,
age SMALLINT NOT NULL,
post_code SMALLINT NOT NULL,
UNIQUE idx_flname_age (first_name,last_name,age)
);
The primary key constraint will do this too, as mentioned by #Ajeesh
EDIT:
As per the suggestion in the comment, if you want to avoid errors generated by this unique constraint, you have three good options:
INSERT IGNORE
and
INSERT...ON DUPLICATE KEY UPDATE
and
REPLACE
INSERT IGNORE will not do anything if the insert violates the unique constraint, except log a harmless warning. The table will be left as is, and no error would be reported. This may be desireable in some cases.
More commonly is the second option, ON DUPLICATE KEY UPDATE, which says "Well, if the key already exists, then update that key's row like this instead."
And lastly is REPLACE, which will, if the key already exists, delete the row, then do an INSERT as normal. If the key did not exist previously, it will simply act as an INSERT.
This stack overflow answer has some examples.
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
You need to call these fields a UNIQUE_KEY
To make a column to be distinct you need to have Primary Key constraint/Unique Key. Primary key is used for relating one table with another and it's values should not be NULL. But in your case you can have Unique constraint to store only unique/distinct values.
I've got a set of staging tables where I accept data, scrub, and cleanse them before inserting to the target table. The target table has a primary key constraint and what I'm inserting is a primary key.
I check for the absence of the primary key in the target table before I insert. I insert only records that ARE NOT in the target table, based on the primary key's absence:
INSERT INTO Target
SELECT
primKey
, user_state
, test_state
FROM
myStagingTable3
By this point, the stagingTable3 has only data that are NOT present in the Target Table using the following where clause:
WHERE
primKey not in (Select primKey from Target)
Somehow, I'm getting a primary key violation error :
Msg 2627, Level 14, State 1. (procedure failed at line #...)
Violation of Primary Key constraint 'pk1101AE.' Cannot insert
duplicate key in object 'Target'
My questions:
under what conditions could a primary key violation occur when the
key that I want to insert is NOT present in the target table?
could a prior delete of records cause the primary key to be retained? If so,
can I work around this somehow?
something else?
It's pretty clear that my staging tables have the key and that the Target table does not. Yet the insert fails.
This happens because your staging table contains multiple rows with the same value of primKey.
If it does not matter to you which {user_state, test_state} pair among the duplicated ones makes it into the insert, you can bypass the issue entirely by adding a simple group by, like this:
INSERT INTO Target
(SELECT
primKey
, MAX(user_state)
, MAX(test_state)
FROM
myStagingTable3
GROUP BY primKey)