Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试使用PHP动态生成和执行DROP语句_Php_Mysql - Fatal编程技术网

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

尝试使用PHP动态生成和执行DROP语句,php,mysql,Php,Mysql,我有php代码,可以解析目录并生成SQL语句,该语句检查特定数据库中是否存在作为表的子目录名,然后为目录中不存在的任何子目录名生成DROP TABLE语句: 在前面的$DIR代码中调用了Directory $directories = glob($DIR . '/*' , GLOB_ONLYDIR); $dir2 = str_replace( "$DIR/" , "" , $directories); $dirlist = implode("', '",$dir2); $sql = "SEL

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

在前面的$DIR代码中调用了Directory

$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语句的正确方法吗?或者如果不在提供的列表中(通过使用CONCAT生成drop语句),是否有更简单的方法编辑我的sql语句来删除这些表?

然后执行以下操作:

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