Logan Shire Logan Shire - 2 months ago 27
MySQL Question

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);

Answer

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");