简体   繁体   中英

PHP/MySQL : How to delete all data from database which contains specific id in one query

In my database i have 32 tables, and most of the tables has contain same ids. How can I delete all the data in the whole database that contains only an specific ID in one query(I mean each tables that contain that specific id).

DELETE * from (ALL TABLES) where id = 3;

Good question. Query might be optimal solution for this.

I have give solutions using PHP here below as PHP tag specified by you

<?php
require("db_connect.php");
$tables = mysqli_query($con, "SHOW TABLES FROM dbname");
while ($row = mysqli_fetch_assoc($tables)) {
    $table_name = $row["Tables_in_dbname"];
    mysqli_query($con, "DELETE FROM $table_name WHERE `id`=3");
}
?>

OR

create one more table where you make daily entries for id which needed to delete from all tables and everyday you might get the different list of id to delete from all tables.

Below here i have created a table ids_to_delete where i specified list of ids to be deleted.

<?php
require("db_connect.php");
//get ids from table where specified ids to be deleted
$ids     = mysqli_query($con, "SELECT `id` FROM `ids_to_delete`");
$id_list = '';
//create ids list like 1,4,3,9,5,6,...
while ($row_id = mysqli_fetch_assoc($tables)) {
    $id_list .= $row_id['id'] . ',';
}
$id_list = trim($id_list, ',');

$tables = mysqli_query($con, "SHOW TABLES FROM dbname");
while ($row = mysqli_fetch_assoc($tables)) {
    $table_name = $row["Tables_in_dbname"];
    mysqli_query($con, "DELETE FROM $table_name WHERE `id` IN ($id_list)");
}
//clear the ids_to_delete table
mysqli_query($con,"DELETE FROM `ids_to_delete`");
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM