Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql: Programmatically remove all foreign keys

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.

like image 597
Zim Avatar asked Mar 19 '26 08:03

Zim


1 Answers

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);
?>
like image 182
Todd Owen Avatar answered Mar 21 '26 05:03

Todd Owen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!