在PHP中,我們可以使用模型來進行數據庫操作,常用的方法包括查詢數據、插入數據、更新數據和刪除數據。以下是一個簡單的示例代碼:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
class UserModel {
private $conn;
public function __construct($conn) {
$this->conn = $conn;
}
public function getUser($id) {
$sql = "SELECT * FROM users WHERE id = $id";
$result = $this->conn->query($sql);
if ($result->num_rows > 0) {
return $result->fetch_assoc();
} else {
return null;
}
}
public function addUser($name, $email) {
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($this->conn->query($sql) === TRUE) {
return true;
} else {
return false;
}
}
public function updateUser($id, $name, $email) {
$sql = "UPDATE users SET name='$name', email='$email' WHERE id=$id";
if ($this->conn->query($sql) === TRUE) {
return true;
} else {
return false;
}
}
public function deleteUser($id) {
$sql = "DELETE FROM users WHERE id=$id";
if ($this->conn->query($sql) === TRUE) {
return true;
} else {
return false;
}
}
}
include 'UserModel.php';
$userModel = new UserModel($conn);
// 查詢數據
$user = $userModel->getUser(1);
echo "User ID: " . $user['id'] . ", Name: " . $user['name'] . ", Email: " . $user['email'] . "<br>";
// 插入數據
if ($userModel->addUser("John Doe", "john.doe@example.com")) {
echo "User added successfully<br>";
} else {
echo "Error adding user<br>";
}
// 更新數據
if ($userModel->updateUser(1, "Jane Smith", "jane.smith@example.com")) {
echo "User updated successfully<br>";
} else {
echo "Error updating user<br>";
}
// 刪除數據
if ($userModel->deleteUser(2)) {
echo "User deleted successfully<br>";
} else {
echo "Error deleting user<br>";
}
通過以上步驟,我們可以很方便地使用PHP模型來進行數據庫操作。需要注意的是,以上代碼僅為示例,實際應用中需要做好數據驗證和安全防護。