简体   繁体   中英

How do you drop a mysql table if the table name is stored as a variable?

I want to drop a table using

//A user is choosing the table to drop.
$name = $_POST['name'];
mysql_connect("localhost", "root", "password") or die (mysql_error ());
mysql_select_db("db_name") or die(mysql_error());
mysql_query('DROP TABLE IF EXISTS `$name`') or die(mysql_error());

If I manually replace "$name" with a table name, it works, so I believe my error has to do with with syntax around dropping a table with a name stored as a variable. Thanks for any help.

In PHP, when using single quotes ('), variables are not expanded. Use double quotes for that:

mysql_query("DROP TABLE IF EXISTS `$name`") or die(mysql_error());

That being said, you should not use the deprecated mysql_ functions anymore, use MySQLi or PDO instead. Also, you are wide open to SQL injections, but I reckon you know that if you do a DROP TABLE with $_POST data, without any validation whatsoever.

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