$dsn = 'mysql:host=localhost;charset=UTF-8'; $dbname = 'newDB'; $username = 'username'; $password = 'password'; try { $pdo = new PDO($dsn, $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec("CREATE DATABASE IF NOT EXISTS $dbname;"); echo "Database created successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "newDB"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Create database $sql = "CREATE DATABASE IF NOT EXISTS $dbname"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $conn->error; } $conn->close();
$servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = mysql_connect($servername, $username, $password); // Check connection if (!$conn) { die('Could not connect: ' . mysql_error()); } // Create database if (mysql_query("CREATE DATABASE IF NOT EXISTS newDB", $conn)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysql_error(); } mysql_close($conn);In summary, the examples provided demonstrate how to create a new database connection using PDO, mysqli, and mysql libraries in PHP. The code creates a connection to the database server and then creates a new database if it does not exist.