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

时间:2013-08-21 14:46:01

标签: php mysql

我有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语句)?

2 个答案:

答案 0 :(得分:0)

然后就这样做:

[...]
$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);

答案 1 :(得分:0)

首先,您需要连接到数据库并运行查询。在循环内部执行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']);
  }
}