Here is the sql error
SQL error: Cannot delete or update a parent row: a foreign key constraint fails (`motioncenter`.`news`, CONSTRAINT `news_ibfk_2` FOREIGN KEY (`fk_categories_id`) REFERENCES `categories` (`category_id`))
Line: 36
Fil: C:\Xampp\htdocs\xampp\site\admin\page_functions\category_delete.php
herre is the category_delete.php file
Line: 36 is echo format_error_message(mysqli_error($database_link), $query, LINE, FILE);
<?php
if ( !isset($database_link))
{
die(header('location: index.php?page=categories'));
}
if ( !isset($_GET['category_id']))
{
die(header('location: index.php?page=categories'));
}
$category_id = ($_GET['category_id'] * 1);
$query = "DELETE FROM categories WHERE category_id = $category_id";
if (mysqli_query($database_link, $query))
{
$_SESSION['message'] .= 'deleted<br />';
die(header('location: index.php?page=categories'));
}
else
{
echo format_error_message(mysqli_error($database_link), $query, __LINE__, __FILE__);
}
?>
Probably your constraint that links items to category prevents you from deleting a category, while some items, news in your example, are still referencing it. Perhaps you should modify your foreign key constraint so that it does cascade delete, like ON DELETE CASCADE
Your database contains foreign keys that have been configured such that you cannot delete categories if there are any news items in that category.
It's kind of like trying to rm a directory that has files in it, you'll get an error saying the directory is not empty.
Add a query to "DELETE FROM news WHERE category_id=".$category_id or update the news items to be in a different category before deleting the category itself.
Deleting a category_id from the category table leads to an error since category_id acts a foreign key in another table. By deleting a value in category_id, all the other instances of that value in other table that reference it will be invalid.
You need to first delete tables with a foreign key referenced to your categories table.
motioncenter.news table has fk_categories_id field with the value you are trying to delete. you need to either delete that row in news table first or use below sql statement to disable foreign checks alltogether.
SET FOREIGN_KEY_CHECKS=0;
First you've to delete all news which is dependent on that category.
Then you can delete that category.
Or alternatively you can change constraint for foreign key:
# Table `motioncenter`.`news`
ALTER TABLE `motioncenter`.`news`
DROP FOREIGN KEY `news_ibfk_2`,
ADD CONSTRAINT `news_ibfk_2` FOREIGN KEY (`fk_categories_id`)
REFERENCES `categories` (`category_id`) ON DELETE CASCADE
Or if you want to keep all related news even then you should change to:
# Table `motioncenter`.`news`
ALTER TABLE `motioncenter`.`news`
DROP FOREIGN KEY `news_ibfk_2`,
ADD CONSTRAINT `news_ibfk_2` FOREIGN KEY (`fk_categories_id`)
REFERENCES `categories` (`category_id`) ON DELETE SET NULL
Because by default foreign key prevent deletion of parent record.
Related
Okay, to explain this.
I ended up creating two tables for my project:
vozaci and ev_gor_km - this is a web app project and ev_gor_km means evident of fuel and km and vozaci means drivers, and in vozaci table I have key called vozac_id and as well I have vozac_id in the table ev_gor_km, therefore I have two pages: one for managing drivers, and other one which among the other information, you're also choosing driver - when you choose driver, you're basically selecting an id which is fetched from table 'vozaci' as vozac_id.
Now, as I've mentioned there's page for managing drivers and there's an option to delete driver - when I click on that "DELETE" button, what happens is that I get an error, why?
Because two reasons actually - first one is because I've updated ev_gor_km's vozac_id KEY with one of vozac_id from table vozaci and the second reason is that I've altered table as follows:
ALTER TABLE `ev_gor_km`
ADD CONSTRAINT `ev_gor_km_ibfk_1` FOREIGN KEY (`vozac_id`) REFERENCES `vozaci` (`vozac_id`),
ADD CONSTRAINT `ev_gor_km_ibfk_2` FOREIGN KEY (`cc_id`) REFERENCES `cost_center` (`cc_id`),
ADD CONSTRAINT `ev_gor_km_ibfk_3` FOREIGN KEY (`car_id`) REFERENCES `car` (`car_id`);
COMMIT;
Now, I know how to solve error in the way that's not really what I want:
ALTER TABLE `ev_gor_km`
ADD CONSTRAINT `ev_gor_km_ibfk_1` FOREIGN KEY (`vozac_id`) REFERENCES `vozaci` (`vozac_id`) ON DELETE CASCADE,
ADD CONSTRAINT `ev_gor_km_ibfk_2` FOREIGN KEY (`cc_id`) REFERENCES `cost_center` (`cc_id`) ON DELETE CASCADE,
ADD CONSTRAINT `ev_gor_km_ibfk_3` FOREIGN KEY (`car_id`) REFERENCES `car` (`car_id`) ON DELETE CASCADE;
COMMIT;
or instead of using ON DELETE CASCADE to use ON DELETE SET NULL.
But, what I actually want to know is How can I have vozac_id in the table ev_gor_km remain same (unchanged) even if the driver from table vozaci with same id is deleted and is it possible at all?
This is my PHP code for deletion(if it matters to somebody):
<?php
require_once(__DIR__ . "/db.php");
$id = $_GET['id'];
try {
$stmt = $conn->prepare("DELETE FROM vozaci WHERE vozac_id = (:id)");
$stmt->bindParam(':id', $id);
$stmt->execute();
header("Location: ../stranica/korisnik.php");
} catch (PDOException $e) {
echo '<p style="red: green;">Greška: " . $e->getMessage(); . "</p>';
}
I have a foreign relationship with category_id column in database but while deleting i get error.
This is my code for delete:
public function destroy($id)
{
$category = Category::find($id);
$category->delete();
Session::flash('success', 'The category was successfully deleted.');
return redirect()->route('categories.index');
}
Error i seen is :
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`fitilicious`.`products`, CONSTRAINT `products_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)) (SQL: delete from `categories` where `id` = 2)
Please help.
My bet is on the foreign key being set to ON DELETE RESTRICT instead of CASCADE.
Cannot delete or update a parent row: a foreign key constraint fails (fitilicious.products, CONSTRAINT products_category_id_foreign FOREIGN KEY (category_id) REFERENCES categories (id)) (SQL: delete from categories where id = 2)
This tells us that there is a row in table "products" which is referencing the category you are attempting to delete.
ON DELETE CASCADE will also delete the product.
ON DELETE RESTRICT will prevent deletion of a non-empty category
ON DELETE SET NULL will delete the category and set category_id to NULL in products table
Each has its uses, but you need to choose which one you need.
sorry, i am still new in php... i want to ask... how actually foreign key is functional? i mean, i have create a foreign key and primary key, everything fine. i try look in internet, but still i cant make it work or did mistake that i dont know. i get this error "Cannot add or update a child row: a foreign key constraint fails" when i try to insert information inside my other table that have foreign key
my parent table "user_information" have:
user_id = primary key
user_password
name
user_category
group_id
and my other "table vehicle_registration" have:
plate_number = primary key
user_id = foreign key
roadtax_validation
vehicle_category
user_option
insurance name
i want to make the user that log in can insert their vehicle registration, and it bind to that user, the user_id should be similar, just other information is diferent... how i can make it? is it correct that the foreign key is to work like that? cause when i try to insert value inside the vehicle_registration it will show "Cannot add or update a child row: a foreign key constraint fails"
can someone explain how it actually done?
You have to add user/s first. You can't add a record in vehicle_registration table if you dont have a matching record in the parent table.
That is how foreign key constraint works. For example if you have a record in user_information table with user_id = 1, you are only allowed to have records with user_id = 1 in the vehicle_registration table. And so on...
so i am trying again and again to make a column as a foreign key but it gives me Constraint name error? what Constraint name should i put? i am using PHPmyadmin SQL , I tried giving it names such as trackid and so on but still i am getting an error
ALTER TABLE `ss_ordered_carts`
ADD CONSTRAINT `track_id` FOREIGN KEY (`track_id`)
REFERENCES `ProjectDatabase`.`ss_orders` (`track_id`)
ON DELETE RESTRICT ON UPDATE CASCADE;
MySQL said: Documentation
1452 - Cannot add or update a child row: a foreign key constraint fails (projectdatabase.
'#sql-1414_6c7'>, CONSTRAINT track_id FOREIGN KEY (track_id) REF
ERENCES ss_orders (track_id) ON UPDATE CASCADE)
If you have data in child table for the referred column field, to add foreign key on that field,
first you have to disable foreign key checking.
And then alter to add foreign key.
And lastly reset the constraint checking.
Step 1: Disable the foreign key checks.
set foreign_key_checks=0;
Step 2: Now add the foreign key constraint.
ALTER TABLE `ss_ordered_carts`
ADD CONSTRAINT `track_id` FOREIGN KEY (`track_id`)
REFERENCES `ProjectDatabase`.`ss_orders` (`track_id`)
ON DELETE RESTRICT ON UPDATE CASCADE;
Step 3: Now reset the foreign key checks.
set foreign_key_checks=1;
It is possible that you have table ss_ordered_carts filled with wrong data, that cannot be related. Check it using this query -
SELECT * FROM ss_ordered_carts t1
LEFT JOIN ss_orders t2
ON t1.track_id = t2.track_id
WHERE
t2.track_id IS NULL;
Then modify table's data, and after, create foreign key.
Try this.
mysql> SET foreign_key_checks = 0;
mysql> ALTER TABLE ss_ordered_carts
ADD CONSTRAINT track_id
FOREIGN KEY(track_id)
REFERENCES ss_orders(track_id)
mysql> SET foreign_key_checks = 1;
May be, you are getting the specified error as there exists data in the tables.
This may also occur if child table contain some data with the foreign key that that are not in parent table. In this case try,
Delete from child where child_id NOT IN (select parent_id from parent where parent.id = child.id)
I would like to know how can I relate 2 id's. One frome users table and another from stats table. The id from users is AI , Primary and I want to relate the other id to this one.
I tried Foreign key constraint (INNODB) and it gave me this error #1452 - Cannot add or update a child row: a foreign key constraint fails (game.#sql-3de_34f, CONSTRAINT ?sql?3de_34f_ibfk_1 FOREIGN KEY (id) REFERENCES user (id)) .
Thanks
Try this!
SET foreign_key_checks = 0;
Then run query to add your key, and after that...
SET foreign_key_checks = 1;
You have USER_IDs in your "stats" table that are not in your "users" table.
Delete them if you think they are not useful anymore.
DELETE FROM stats where user_id NOT IN (SELECT user_id from users);
Then, you can create your reference keys.