0

I am trying to learn PHP and as part of this am writing a small setup script. I have written one before and it worked, however, I have now written a multistage setup.php script and am getting a syntax error when executing the following prepared MySQL statement:

$sql = $connection->prepare( "CREATE DATABASE IF NOT EXISTS ?" );
$sql->execute( array( $database_name ) );

Where $database_name is provided by a form. I have done a var_dump on $database_name and it has the value I provide to it by the form. However, when executing the statement, I get the following error:

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 "cv_database" at line 1

Does anyone have any idea what could be causing this?

Thomas Russell
  • 5,870
  • 4
  • 33
  • 68
  • 2
    You can't use parameters for MYSQL identifiers like table or column names –  Feb 23 '15 at 10:42
  • Perhaps you can't use wildcards for database names? – hd1 Feb 23 '15 at 10:43
  • Share the db name you provided through the form. – Ataboy Josef Feb 23 '15 at 10:44
  • Are you doing it on an online web server? Then I think they don't provide provision to create database via code. – Akhilesh B Chandran Feb 23 '15 at 10:44
  • @RocketSurgeon I gave it "cv_database", is that what you're asking for? – Thomas Russell Feb 23 '15 at 10:45
  • @AkhileshBChandran No, I'm doing it on my local machine using Desktop Server, and I know that it works if I just use `$connection->exec( "CREATE DATABASE IF NOT EXISTS " . $database_name );` but I thought that using prepared statements would be safer. – Thomas Russell Feb 23 '15 at 10:46
  • 1
    @Shaktal That's the only way you can create this sort of query. Be sure to sanitize & escape the user-supplied string before inserting it into your query. –  Feb 23 '15 at 10:49
  • Yeah @HoboSapiens seems to be right. You can't use placeholders for database name, table names, column names in PDO. The answer here also mentions the same: http://stackoverflow.com/questions/18988935/sqlstate42000-syntax-error-or-access-violation-1064 – Akhilesh B Chandran Feb 23 '15 at 10:51
  • @HoboSapiens I have tried the following and am getting the same syntax error? `$sql = "CREATE DATABASE IF NOT EXISTS " . $connection->quote( $database_name ); $connection->exec( $sql );` – Thomas Russell Feb 23 '15 at 11:07

0 Answers0