Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Database If Not Exists with PDO

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);
like image 544
Logan Shire Avatar asked Nov 14 '13 18:11

Logan Shire


1 Answers

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");
like image 101
Your Common Sense Avatar answered Nov 07 '22 12:11

Your Common Sense