在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
替換為你自己的數據庫憑據。