下面是一个使用PHP PDO连接MySQL数据库进行增删改查的实例:
<?php
$host = 'localhost';
$dbname = 'your_database_name';
$username = 'your_username';
$password = 'your_password';
try { $conn = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "成功连接到数据库"; } catch(PDOException $e) { echo "连接数据库失败:" . $e->getMessage(); } ?>
2. 插入数据:
```php
<?php
// 假设数据为:
$name = "John";
$age = 25;
$email = "john@example.com";
$sql = "INSERT INTO your_table_name (name, age, email) VALUES (?, ?, ?)";
try {
$stmt = $conn->prepare($sql);
$stmt->execute([$name, $age, $email]);
echo "插入数据成功";
} catch(PDOException $e) {
echo "插入数据失败:" . $e->getMessage();
}
?>
<?php
// 假设要更新的数据为:
$id = 1;
$newEmail = "new_email@example.com";
$sql = "UPDATE your_table_name SET email = ? WHERE id = ?";
try { $stmt = $conn->prepare($sql); $stmt->execute([$newEmail, $id]);
echo "更新数据成功";
} catch(PDOException $e) { echo "更新数据失败:" . $e->getMessage(); } ?>
4. 删除数据:
```php
<?php
// 假设要删除的数据id为:
$id = 1;
$sql = "DELETE FROM your_table_name WHERE id = ?";
try {
$stmt = $conn->prepare($sql);
$stmt->execute([$id]);
echo "删除数据成功";
} catch(PDOException $e) {
echo "删除数据失败:" . $e->getMessage();
}
?>
<?php
// 假设要查询的数据条件为:
$name = "John";
$sql = "SELECT * FROM your_table_name WHERE name = ?";
try { $stmt = $conn->prepare($sql); $stmt->execute([$name]);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
echo "ID: " . $row['id'] . "<br>";
echo "Name: " . $row[' echo "Age: " . $row['age'] . "<br>";
echo "Email: " . $row['email'] . "<br>";
echo "<br>";
}
} catch(PDOException $e) { echo "查询数据失败:" . $e->getMessage(); } ?>
请确保将上述示例代码中的"your_database_name"替换为你实际的数据库名称,"your_username"和"your_password"替换为你的数据库用户名和密码,"your_table_name"替换为你的表名。