10

I'm trying to create a database-install PHP file that first attempts to create a database if it does not already exist using a PDO prepared statement that I execute, and then I would like to connect to this. Is this how I would do it? Or is there something I'm missing here?

$mysql = new PDO("mysql:host=localhost", $dbusername, $dbpassword);
$pstatement = $mysql->prepare("CREATE DATABASE IF NOT EXISTS $dbname");
$pstatment->execute();
$dbconn = new PDO("mysql:host=localhost;dbname=$dbname", $dbusername, $dbpassword);
8
  • 5
    why would do you want to create a database with PDO? Do you understand that you are NOT using prepared statement here (although you can't but anyway)? Commented Nov 14, 2013 at 18:46
  • @Your Common Sense Normally I would just use phpMyAdmin to actually create the database but for some random reason our professor wants us to do it this way. Commented Nov 14, 2013 at 18:48
  • @oGeez, thanks. I just updated it. Commented Nov 14, 2013 at 18:49
  • 1
    Okay, but I'm in agreement with @YourCommonSense. I can't think of a time when you would need to create this way. Commented Nov 14, 2013 at 18:52
  • 7
    If you are creating a new database for a new user on your web app (as an example), you might want to use PDO to create the database. Not because it allows for prepared statements here (because it doesn't) but because you're using PDO for the rest of the entire project. There's no point in making different kinds of connections, or mixing up code. If you're going to use PDO to interact with the database, you might as well use PDO to create the database. Commented Mar 21, 2015 at 18:45

1 Answer 1

29

Slightly more sensible and safe code.

$pdo = new PDO("mysql:host=localhost", $dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$dbname = "`".str_replace("`","``",$dbname)."`";
$pdo->query("CREATE DATABASE IF NOT EXISTS $dbname");
$pdo->query("use $dbname");
Sign up to request clarification or add additional context in comments.

1 Comment

I just tried mine and it worked, but I'm gonna give this to you because yours is safer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.