5

I would like to drop a database using PDO.

This approach was the best one to me

function delete_db($database)
{
  $statement = $my_pdo_obj->prepare("DROP DATABASE IF EXISTS :database");
  $statement->bindParam(":database", $database);
  $statement->execute();
}

But unfortunately, I got a PDOException saying that there is a syntax error near my binded value ($database) :

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1'

So I tried to perform the query as follow

function delete_db($database)
{
  $statement = $my_pdo_obj->exec("DROP DATABASE IF EXISTS " . $database);
}

And it works.

I was wondering why the prepared statement was not working and also, if the second query was secured.

Thanks in advance for your ideas !

Xor
  • 199
  • 1
  • 2
  • 8

2 Answers2

5

You can't use binding values for table names, database names etc.

http://php.net/manual/ru/pdo.prepare.php#111977

Artem Ilchenko
  • 1,050
  • 9
  • 20
0

As far as I know PDO only accepts bindings for column names.

Maybe this question helps you!

Can PHP PDO Statements accept the table or column name as parameter?

Community
  • 1
  • 1
Matthias Weiß
  • 508
  • 7
  • 17