Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore MySQL foreign key constraints in PHP

Is there a way to override mysql foreign key constraints in a php script?

I have a query passed to mysql from php, but it fails a foreign key constraint, is there any way to get around this without altering the db schema?

I'm just doing some testing, so I'll be removing the row when I'm done.

like image 737
Parris Varney Avatar asked Nov 24 '10 16:11

Parris Varney


People also ask

How do you ignore foreign key constraints?

To disable a foreign key constraint for INSERT and UPDATE statements. In Object Explorer, expand the table with the constraint and then expand the Keys folder. Right-click the constraint and select Modify. In the grid under Table Designer, select Enforce Foreign Key Constraint and select No from the drop-down menu.

Can we disable foreign key constraint MySQL?

You can disable a foreign key constraint during INSERT and UPDATE transactions in SQL Server by using SQL Server Management Studio or Transact-SQL. Use this option if you know that new data will not violate the existing constraint or if the constraint applies only to the data already in the database.

How do I disable foreign key checks in MySQL?

You can disable foreign key check in MySQL by setting the system variable foreign_key_checks to 0. However, please note, after you enable foreign key checks, MySQL will not re-validate your existing data that you added after disabling foreign key check. It will only check any new additions/updates to your database.


2 Answers

$pdo->query('SET foreign_key_checks = 0');
//do some stuff here
$pdo->query('SET foreign_key_checks = 1');
like image 122
TomaszSobczak Avatar answered Sep 22 '22 01:09

TomaszSobczak


You can execute that MySQL query to disable foreign keys check:

SET FOREIGN_KEY_CHECKS=0;

Don't forget to enable it when you're done:

SET FOREIGN_KEY_CHECKS=1;
like image 21
netcoder Avatar answered Sep 20 '22 01:09

netcoder