Logan Shire Logan Shire - 1 year ago 198
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");
$dbconn = new PDO("mysql:host=localhost;dbname=$dbname", $dbusername, $dbpassword);

Answer Source

Slightly more sensible and safe code.

$pdo = new PDO("mysql:host=localhost", $dbusername, $dbpassword);

$dbname = "`".str_replace("`","``",$dbname)."`";
$pdo->query("CREATE DATABASE IF NOT EXISTS $dbname");
$pdo->query("use $dbname");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download