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);
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With