PHP MySQL 创建数据库

在本教程中,你将学习如何使用 PHP 在 MySQL 中创建数据库。

使用 PHP 创建 MySQL 数据库

现在你已经了解了如何打开与 MySQL 数据库服务器的连接。在本教程中,你将学习如何执行 SQL 查询来创建数据库。

在保存或访问数据之前,我们需要先创建一个数据库。该语句用于在 MySQL 中创建新数据库。 CREATE DATABASE

让我们使用该 CREATE DATABASE 语句进行 SQL 查询,之后我们将通过将其传递给 PHP mysqli_query() 函数来执行此 SQL 查询,以最终创建我们的数据库。以下示例创建名为 demo 的数据库。

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
 
// Attempt create database query execution
$sql = "CREATE DATABASE demo";
if(mysqli_query($link, $sql)){
    echo "Database created successfully";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
 
// Close connection
mysqli_close($link);
?>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "root", "");
 
// Check connection
if($mysqli === false){
    die("ERROR: Could not connect. " . $mysqli->connect_error);
}
 
// Attempt create database query execution
$sql = "CREATE DATABASE demo";
if($mysqli->query($sql) === true){
    echo "Database created successfully";
} else{
    echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}
 
// Close connection
$mysqli->close();
?>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try{
    $pdo = new PDO("mysql:host=localhost;", "root", "");
    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
 
// Attempt create database query execution
try{
    $sql = "CREATE DATABASE demo";
    $pdo->exec($sql);
    echo "Database created successfully";
} catch(PDOException $e){
    die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
 
// Close connection
unset($pdo);
?>

提示: 设置 PDO::ATTR_ERRMODE 属性以 PDO::ERRMODE_EXCEPTION 告知 PDO 在发生数据库错误时抛出异常。