要簡化PHP和MySQL類操作,你可以使用一些流行的PHP庫,如MySQLi和PDO。這些庫提供了更簡潔、更安全、更易于使用的接口來執行數據庫操作。下面是使用MySQLi和PDO的簡單示例。
1. MySQLi
MySQLi是MySQL Improved的縮寫,它提供了一個面向對象的接口來與MySQL數據庫進行交互。以下是一個簡單的示例:
// 創建連接
$mysqli = new mysqli("localhost", "username", "password", "database");
// 檢查連接
if ($mysqli->connect_error) {
die("連接失敗: " . $mysqli->connect_error);
}
// 插入數據
$sql = "INSERT INTO users (name, email) VALUES ('張三', 'zhangsan@example.com')";
if ($mysqli->query($sql) === TRUE) {
echo "新記錄插入成功";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
// 查詢數據
$sql = "SELECT id, name, email FROM users";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 結果";
}
// 關閉連接
$mysqli->close();
2. PDO
PDO(PHP Data Objects)是一個在PHP中訪問數據庫的輕量級、一致性的接口。以下是一個簡單的示例:
// 創建連接
$dsn = "mysql:host=localhost;dbname=database";
$username = "username";
$password = "password";
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
);
try {
$pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
die("連接失敗: " . $e->getMessage());
}
// 插入數據
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$name = '張三';
$email = 'zhangsan@example.com';
$stmt->execute();
// 查詢數據
$sql = "SELECT id, name, email FROM users";
$stmt = $pdo->query($sql);
while ($row = $stmt->fetch()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
// 關閉連接
$pdo = null;
使用這些庫可以讓你更方便地執行數據庫操作,同時它們還提供了許多高級功能,如預處理語句、事務控制和安全性。