I'm working with a bit of a dodgey database at the moment, there are foreign keys defined in all the wrong places all over the place, I'd like to remove them all and then start from scratch. I don't wish to remove the column, just the foreign key relationships.
How can I remove all foreign keys from an entire database? (Or table by table).
Thanks.
Edit: Forgot to say, I have PHPMyAdmin available to use.
Here's a PHP script to loop through the information_schema.key_column_usage table and drop each foreign key:
<?php
$DBNAME = 'your db name';
$USER = 'username';
$PASSWORD = 'your password';
$SERVER = 'localhost'; //Or Write your IP Address
$conexion = new mysqli($SERVER,$USER,$PASSWORD,$DBNAME);
$SQL = "SELECT DISTINCT table_name, constraint_name"
." FROM information_schema.key_column_usage"
." WHERE constraint_schema = '$DBNAME'"
." AND referenced_table_name IS NOT NULL";
$result = mysqli_query($conexion, $SQL);
while($row = mysqli_fetch_assoc($result)) {
mysqli_query($conexion, "ALTER TABLE `$row[table_name]`"
."DROP FOREIGN KEY `$row[constraint_name]`")
or die(mysqli_error());
}
mysqli_close($conexion);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With