要使用PHP和MySQL類操作數據庫表,首先確保已經安裝了MySQL服務器和PHP的MySQL擴展(如MySQLi或PDO)。以下是使用MySQLi擴展操作數據庫表的示例步驟:
$servername = "localhost"; // 服務器地址
$username = "your_username"; // 用戶名
$password = "your_password"; // 密碼
$dbname = "your_database"; // 數據庫名
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
echo "連接成功";
$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL
)";
if ($conn->query($sql) === TRUE) {
echo "數據表創建成功";
} else {
echo "創建數據表錯誤: " . $conn->error;
}
$username = "testuser";
$email = "testuser@example.com";
$password = password_hash("testpassword", PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $username, $email, $password);
if ($stmt->execute() === TRUE) {
echo "新記錄插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt->close();
$sql = "SELECT id, username, email, password FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 輸出每行數據
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["username"]. " - Email: " . $row["email"]. " - Password: " . $row["password"]. "<br>";
}
} else {
echo "0 結果";
}
$result->free();
$id = 1;
$new_username = "updated_username";
$new_email = "updated_email@example.com";
$sql = "UPDATE users SET username = ?, email = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $new_username, $new_email, $id);
if ($stmt->execute() === TRUE) {
echo "記錄更新成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt->close();
$id = 1;
$sql = "DELETE FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
if ($stmt->execute() === TRUE) {
echo "記錄刪除成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt->close();
$conn->close();
請注意,這只是一個簡單的示例。在實際項目中,建議使用PHP框架(如Laravel或Symfony)和ORM(對象關系映射)庫來操作數據庫表,以提高代碼的可維護性和安全性。