1

我正在编写一个函数,如果它已经存在,它将删除一个表。它将询问用户他们想调用什么表,获取该响应并将其放入 php 变量中。我想为 sql 创建一个自定义的 drop 语句,以便 sql 没有错误。这就是我所拥有的。

$table = $_POST["tablename"];      //gets table name from html page

drop_table($db, $table);           //call function

function drop_table($db,$table){            
    $drop = "DROP TABLE IF EXISTS .$table. ";     //this is the part I can't figure out. How do I add in the table name to the statement, 
    $q = mysqli_query($db, $drop); //since the sql statement has to be in quotes?
} 

谢谢!

P.Ss 这是一个仅用于分析的内部系统。如果我和我的同事都在使用它,不用担心丢桌子

4

2 回答 2

4

您的问题是尝试$table用点连接时出现语法错误。删除那些。

$drop = "DROP TABLE IF EXISTS $table ";  

更大的问题是您允许最终用户删除数据库中的任何表,因为您没有以任何方式过滤输入。

您需要确保您的用户只在当前选定的数据库中删除表,这意味着至少不允许.内部$table阻止类似的事情$table = 'information_schema.user'

if (strpos($table, '.') !== FALSE) {
  // don't allow the action!
}

要采取的另一个步骤是在执行语句之前验证 的值是否$table存在于information_schema.TABLES并且属于正确的当前数据库。DROP

// If this returns 1, the table exists in the correct database and can be dropped.
// note that $table is escaped here.  I didn't fill in the mysqli_query() but obviously
// this is to be executed.  It would be even better with a MySQLi prepared statement
"SELECT 1 
 FROM information_schema.TABLES
 WHERE
   TABLE_SCHEMA='the_allowed_database' 
   AND TABLE_NAME='" . mysqli_real_escape_string($db, $table) . "'"`

通过此检查后,您最好为在环境中灵活并因此可以删除的表指定一个前缀,这样用户就无法删除活动数据库中的每个表。例如,只允许删除前缀为 的表usertable_

if (strpos($table, 'usertable_') !== 0) {
   // don't permit deletion
}

这是一个非常难以保护的设计,我建议您退后一步,重新考虑这里的策略。在允许用户根据表单输入删除表时,您需要非常小心。

于 2012-06-22T16:50:33.320 回答
3

你的意思是:

$drop = "DROP TABLE IF EXISTS " . $table;

我真的,真的希望您已经考虑过有人能够通过在 URL 中输入正确的名称从您的数据库中删除表的后果。

于 2012-06-22T16:50:36.127 回答