在PHP中,你可以使用MySQLi或PDO扩展来创建数据库表。以下是使用这两种方法的示例:
方法1:使用MySQLi
<?php
// 连接到MySQL数据库
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 创建表的SQL语句
$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
email VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
// 执行SQL语句并检查是否成功
if ($conn->query($sql) === TRUE) {
echo "表users创建成功";
} else {
echo "创建表错误: " . $conn->error;
}
// 关闭连接
$conn->close();
?>
方法2:使用PDO
<?php
// 连接到MySQL数据库
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";
try {
// 创建连接
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 创建表的SQL语句
$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
email VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
// 执行SQL语句并检查是否成功
$conn->exec($sql);
echo "表users创建成功";
} catch(PDOException $e) {
echo "创建表错误: " . $e->getMessage();
}
// 关闭连接
$conn = null;
?>
请注意,你需要将your_username
、your_password
和your_dbname
替换为你自己的数据库凭据。