实例 (MySQLi - 面向对象)
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = new mysqli($servername, $username, $password); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 创建数据库 $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "数据库创建成功"; } else { echo "Error creating database: " . $conn->error; } $conn->close(); ?>
注意: 当你创建一个新的数据库时,你必须为 mysqli 对象指定三个参数 (servername, username 和 password)。 Tip: 如果你使用其他端口(默认为3306),为数据库参数添加空字符串,如: new mysqli("localhost", "username", "password", "", port) |
实例 (MySQLi Procedural)
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = mysqli_connect($servername, $username, $password); // 检测连接 if (!$conn) { die("连接失败: " . mysqli_connect_error()); } // 创建数据库 $sql = "CREATE DATABASE myDB"; if (mysqli_query($conn, $sql)) { echo "数据库创建成功"; } else { echo "Error creating database: " . mysqli_error($conn); } mysqli_close($conn); ?>
实例
使用 PDO:
<?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername", $username, $password); // 设置 PDO 错误模式为异常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "CREATE DATABASE myDBPDO"; // 使用 exec() ,因为没有结果返回 $conn->exec($sql); echo "数据库创建成功<br>"; } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?>