在PHP中,我們可以使用模型來進行數(shù)據(jù)庫操作,常用的方法包括查詢數(shù)據(jù)、插入數(shù)據(jù)、更新數(shù)據(jù)和刪除數(shù)據(jù)。以下是一個簡單的示例代碼:
$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);
// 查詢數(shù)據(jù)
$user = $userModel->getUser(1);
echo "User ID: " . $user['id'] . ", Name: " . $user['name'] . ", Email: " . $user['email'] . "<br>";
// 插入數(shù)據(jù)
if ($userModel->addUser("John Doe", "john.doe@example.com")) {
echo "User added successfully<br>";
} else {
echo "Error adding user<br>";
}
// 更新數(shù)據(jù)
if ($userModel->updateUser(1, "Jane Smith", "jane.smith@example.com")) {
echo "User updated successfully<br>";
} else {
echo "Error updating user<br>";
}
// 刪除數(shù)據(jù)
if ($userModel->deleteUser(2)) {
echo "User deleted successfully<br>";
} else {
echo "Error deleting user<br>";
}
通過以上步驟,我們可以很方便地使用PHP模型來進行數(shù)據(jù)庫操作。需要注意的是,以上代碼僅為示例,實際應(yīng)用中需要做好數(shù)據(jù)驗證和安全防護。