如果不使用 PDO,可以使用 MySQLi(MySQL Improved)扩展来实现 PHP 和 MySQL 的增删改查操作,并结合预处理语句(Prepared Statements)来防止 SQL 注入攻击。以下是详细的实现步骤:
1. 连接数据库
使用 mysqli_connect() 函数连接到 MySQL 数据库。
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'test_db';
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
echo "连接成功";
?>
2. 插入数据(Create)
<?php
$name = "John Doe";
$email = "john@example.com";
$stmt = mysqli_prepare($conn, "INSERT INTO users (name, email) VALUES (?, ?)");
mysqli_stmt_bind_param($stmt, "ss", $name, $email);
if (mysqli_stmt_execute($stmt)) {
echo "新记录插入成功";
} else {
echo "插入失败: " . mysqli_error($conn);
}
mysqli_stmt_close($stmt);
?>
3. 查询数据(Read)
<?php
$stmt = mysqli_prepare($conn, "SELECT id, name, email FROM users");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $name, $email);
while (mysqli_stmt_fetch($stmt)) {
echo "ID: $id, Name: $name, Email: $email<br>";
}
mysqli_stmt_close($stmt);
?>
4. 更新数据(Update)
<?php
$id = 1;
$newEmail = "john.new@example.com";
$stmt = mysqli_prepare($conn, "UPDATE users SET email = ? WHERE id = ?");
mysqli_stmt_bind_param($stmt, "si", $newEmail, $id);
if (mysqli_stmt_execute($stmt)) {
echo "记录更新成功";
} else {
echo "更新失败: " . mysqli_error($conn);
}
mysqli_stmt_close($stmt);
?>
5. 删除数据(Delete)
<?php
$id = 1;
$stmt = mysqli_prepare($conn, "DELETE FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $id);
if (mysqli_stmt_execute($stmt)) {
echo "记录删除成功";
} else {
echo "删除失败: " . mysqli_error($conn);
}
mysqli_stmt_close($stmt);
?>
6. 关闭数据库连接
<?php
mysqli_close($conn);
?>
7. 完整示例
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'test_db';
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
$name = "John Doe";
$email = "john@example.com";
$stmt = mysqli_prepare($conn, "INSERT INTO users (name, email) VALUES (?, ?)");
mysqli_stmt_bind_param($stmt, "ss", $name, $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$stmt = mysqli_prepare($conn, "SELECT id, name, email FROM users");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $name, $email);
while (mysqli_stmt_fetch($stmt)) {
echo "ID: $id, Name: $name, Email: $email<br>";
}
mysqli_stmt_close($stmt);
$id = 1;
$newEmail = "john.new@example.com";
$stmt = mysqli_prepare($conn, "UPDATE users SET email = ? WHERE id = ?");
mysqli_stmt_bind_param($stmt, "si", $newEmail, $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$id = 1;
$stmt = mysqli_prepare($conn, "DELETE FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>
总结
- 使用 MySQLi 扩展可以实现 PHP 和 MySQL 的增删改查操作。
- 预处理语句(Prepared Statements)可以有效防止 SQL 注入攻击。
- 相比于 PDO,MySQLi 更专注于 MySQL 数据库,适合不需要跨数据库兼容性的项目。
通过以上方法,你可以在不使用 PDO 的情况下,安全高效地操作 MySQL 数据库。