Question: PHP/MYSQL - Drop database using prepared statement

Question

PHP/MYSQL - Drop database using prepared statement

Answers 2
Added at 2017-01-02 18:01
Tags
Question

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 !

Answers
nr: #1 dodano: 2017-01-02 18:01

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?

nr: #2 dodano: 2017-01-02 18:01

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

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

Source Show
◀ Wstecz