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 !

0

1 Answer 1

5

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer ! What about the second one, should I keep it ?
If you need do this from your application, why not. But don't forget protect from SQL injections

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.