Gasperro
Gasperro

Reputation: 25

How to delete data from 2 tables in one mysql query in php?

I need to delete a country with specific id and cities that belong to that country . I looked this up all over stack overflow and came up with this, but it still doesn't execute it..

if(isset($_POST['id'])){
        $id =($_POST['id']);}

    $connection = mysqli_connect("localhost", "root", "", "lol");
    if ($connection-> connect_error) {
        die("Connection failed:". $connection-> connect_error);
    }
    $sql= "DELETE `countries`, `cities` FROM `countries` INNER JOIN `cities` on 
    `cities.fk_Country` = `countries.id` WHERE `countries.id` = $id";
    var_dump($sql);
    if(!mysqli_query($connection,$sql)){
        echo 'Unable to delete the country. Try again!';
    } else {
        echo 'Succesfully deleted the country!';
    }

Upvotes: 0

Views: 95

Answers (1)

Ed Bangga
Ed Bangga

Reputation: 13006

delete your cities first since it has foreign key from countries.

$sql= "delete cities, countries
     from cities
     inner join countries on cities.fk_Country = countries.id
     where countries.id=$id";

Upvotes: 1

Related Questions