在PHP中,你可以使用MySQLi或PDO擴(kuò)展來(lái)創(chuàng)建數(shù)據(jù)庫(kù)表。以下是使用這兩種方法的示例:
方法1:使用MySQLi
<?php
// 連接到MySQL數(shù)據(jù)庫(kù)
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";
// 創(chuàng)建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
// 創(chuàng)建表的SQL語(yǔ)句
$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
)";
// 執(zhí)行SQL語(yǔ)句并檢查是否成功
if ($conn->query($sql) === TRUE) {
echo "表users創(chuàng)建成功";
} else {
echo "創(chuàng)建表錯(cuò)誤: " . $conn->error;
}
// 關(guān)閉連接
$conn->close();
?>
方法2:使用PDO
<?php
// 連接到MySQL數(shù)據(jù)庫(kù)
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";
try {
// 創(chuàng)建連接
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 設(shè)置 PDO 錯(cuò)誤模式為異常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 創(chuàng)建表的SQL語(yǔ)句
$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
)";
// 執(zhí)行SQL語(yǔ)句并檢查是否成功
$conn->exec($sql);
echo "表users創(chuàng)建成功";
} catch(PDOException $e) {
echo "創(chuàng)建表錯(cuò)誤: " . $e->getMessage();
}
// 關(guān)閉連接
$conn = null;
?>
請(qǐng)注意,你需要將your_username
、your_password
和your_dbname
替換為你自己的數(shù)據(jù)庫(kù)憑據(jù)。