尝试使用PHP动态生成和执行DROP语句


Attempting to dynamically generate and execute DROP statements using PHP

我有php代码,它解析目录并生成SQL语句,该语句检查特定数据库中是否存在作为表的子目录名,然后为目录中不存在的任何子目录名生成DROP TABLE语句:

目录是在$DIR代码的早期调用的。

$directories = glob($DIR . '/*' , GLOB_ONLYDIR);
$dir2 = str_replace( "$DIR/"  , ""  , $directories);
$dirlist = implode("', '",$dir2);
$sql = "SELECT CONCAT('DROP TABLE ', table_name, ';') FROM information_schema.TABLES WHERE table_schema = 'streamer1' AND table_name NOT IN ('$dirlist');";
echo "$sql";

这将在我的浏览器窗口中生成一条SQL语句。当我使用mysql手动运行sql语句时,我会得到任何未在文件夹中作为子目录名称找到的表名称所需的DROP TABLE语句列表。

+----------------------------------------+
| CONCAT('DROP TABLE ', table_name, ';') |
+----------------------------------------+
| DROP TABLE jhtest;                     |
+----------------------------------------+
1 row in set (0.00 sec)

我想完成的是获取这些结果,并使用我的php代码在mysql中执行它们。我目前正停留在返回php中的结果,然后将每个结果作为mysql语句执行。

这是生成这些drop语句的正确方法吗?或者,如果不在提供的列表中,是否有一种更简单的方法可以编辑我的sql语句来drop这些表(而不是使用CONCAT来生成drop语句)?

然后就这样做:

[...]
$sql = "SELECT CONCAT('DROP TABLE ', table_name, ';') FROM information_schema.TABLES WHERE table_schema = 'streamer1' AND table_name NOT IN ('$dirlist');";
$result = mysql_query($sql, $connection);
while ($row = mysql_fetch_array($result))
    mysql_query($row[0], $connection);

首先需要连接到数据库并运行查询。在循环中执行drop语句。

$con = mysql_connect("host","username","password");
mysql_select_db("information_schema", $con) or die(mysql_error());
$sql = "SELECT CONCAT('DROP TABLE ', table_name, ';') as q FROM information_schema.TABLES WHERE table_schema = 'streamer1' AND table_name NOT IN ('$dirlist');";
//run the query
$res = mysql_query($sql);
if(!$res){
  die(mysql_error());
} else {
  while($row = mysql_fetch_array($res)){
    echo $row['q']."'n"; //output the queries or run the drop statements like this
    mysql_query($row['q']);
  }
}