Appearance
12.4 添加数据 insert
INSERT 语句基础
INSERT 语句用于向数据库表中插入新记录,是数据库操作中最基本的操作之一。
基本语法
sql
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);基本插入
1. 插入单条记录
php
<?php
require_once 'db.php';
$conn = getDbConnection();
// 插入单条记录
$sql = "INSERT INTO users (username, email, password) VALUES ('user7', 'user7@example.com', 'password123')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功,ID: " . $conn->insert_id;
} else {
echo "插入失败: " . $conn->error;
}
$conn->close();
?>2. 插入多条记录
php
<?php
require_once 'db.php';
$conn = getDbConnection();
// 插入多条记录
$sql = "INSERT INTO users (username, email, password) VALUES
('user8', 'user8@example.com', 'password123'),
('user9', 'user9@example.com', 'password456'),
('user10', 'user10@example.com', 'password789')";
if ($conn->query($sql) === TRUE) {
echo "多条记录插入成功,最后插入的ID: " . $conn->insert_id;
} else {
echo "插入失败: " . $conn->error;
}
$conn->close();
?>使用预处理语句
预处理语句可以防止 SQL 注入攻击,同时提高执行效率。
1. 插入单条记录
php
<?php
require_once 'db.php';
$conn = getDbConnection();
// 准备语句
$stmt = $conn->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $email, $password);
// 设置参数并执行
$username = "user11";
$email = "user11@example.com";
$password = "password123";
if ($stmt->execute()) {
echo "新记录插入成功,ID: " . $conn->insert_id;
} else {
echo "插入失败: " . $stmt->error;
}
$stmt->close();
$conn->close();
?>2. 插入多条记录
php
<?php
require_once 'db.php';
$conn = getDbConnection();
// 准备语句
$stmt = $conn->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $email, $password);
// 要插入的数据
$users = [
['user12', 'user12@example.com', 'password123'],
['user13', 'user13@example.com', 'password456'],
['user14', 'user14@example.com', 'password789']
];
// 执行多次插入
$successCount = 0;
foreach ($users as $user) {
$username = $user[0];
$email = $user[1];
$password = $user[2];
if ($stmt->execute()) {
$successCount++;
}
}
echo "成功插入 $successCount 条记录";
$stmt->close();
$conn->close();
?>插入数据与表单结合
1. 基本表单处理
php
<?php
require_once 'db.php';
$conn = getDbConnection();
$errors = [];
$success = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 表单验证
if (empty($_POST['username'])) {
$errors[] = '用户名不能为空';
}
if (empty($_POST['email'])) {
$errors[] = '邮箱不能为空';
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = '邮箱格式不正确';
}
if (empty($_POST['password'])) {
$errors[] = '密码不能为空';
}
if (empty($errors)) {
// 准备语句
$stmt = $conn->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $email, $password);
// 设置参数
$username = htmlspecialchars($_POST['username']);
$email = htmlspecialchars($_POST['email']);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
if ($stmt->execute()) {
$success = true;
} else {
$errors[] = '插入失败: ' . $stmt->error;
}
$stmt->close();
}
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>添加用户</title>
<style>
body { font-family: Arial, sans-serif; max-width: 400px; margin: 0 auto; padding: 20px; }
.error { color: red; }
.success { color: green; }
input { width: 100%; padding: 10px; margin: 5px 0; }
input[type="submit"] { background-color: #4CAF50; color: white; border: none; cursor: pointer; }
</style>
</head>
<body>
<h2>添加用户</h2>
<?php if (!empty($errors)): ?>
<div class="error">
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php if ($success): ?>
<div class="success">
用户添加成功!
</div>
<?php endif; ?>
<form action="" method="post">
<label>用户名: <input type="text" name="username"></label><br>
<label>邮箱: <input type="email" name="email"></label><br>
<label>密码: <input type="password" name="password"></label><br>
<input type="submit" value="添加用户">
</form>
</body>
</html>插入数据时的注意事项
1. 数据类型匹配
确保插入的值与表字段的数据类型匹配:
- 字符串类型:使用引号包围
- 数字类型:直接使用,不使用引号
- 日期类型:使用引号包围,格式为 'YYYY-MM-DD'
- 布尔类型:使用 1 或 0
2. 转义特殊字符
使用预处理语句或 mysqli_real_escape_string 函数转义特殊字符:
php
// 使用 mysqli_real_escape_string
$username = mysqli_real_escape_string($conn, $_POST['username']);
$sql = "INSERT INTO users (username) VALUES ('$username')";3. 处理自动增长字段
对于 AUTO_INCREMENT 字段,不需要指定值,MySQL 会自动生成:
php
// id 是 AUTO_INCREMENT 字段
$sql = "INSERT INTO users (username, email) VALUES ('user15', 'user15@example.com')";4. 处理默认值
对于有默认值的字段,可以不指定值,使用默认值:
php
// created_at 有默认值 CURRENT_TIMESTAMP
$sql = "INSERT INTO users (username, email) VALUES ('user16', 'user16@example.com')";事务处理
对于需要插入多条相关记录的情况,使用事务确保数据一致性:
php
<?php
require_once 'db.php';
$conn = getDbConnection();
// 开始事务
$conn->begin_transaction();
try {
// 插入用户
$stmt = $conn->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $email, $password);
$username = "user17";
$email = "user17@example.com";
$password = "password123";
$stmt->execute();
$userId = $conn->insert_id;
// 插入用户资料
$stmt = $conn->prepare("INSERT INTO user_profiles (user_id, full_name, age) VALUES (?, ?, ?)");
$stmt->bind_param("isi", $userId, $fullName, $age);
$fullName = "测试用户";
$age = 25;
$stmt->execute();
// 提交事务
$conn->commit();
echo "用户和资料添加成功";
} catch (mysqli_sql_exception $e) {
// 回滚事务
$conn->rollback();
echo "添加失败: " . $e->getMessage();
}
$stmt->close();
$conn->close();
?>批量插入
对于大量数据的插入,使用批量插入可以提高性能:
php
<?php
require_once 'db.php';
$conn = getDbConnection();
// 批量插入
$values = [];
for ($i = 18; $i <= 28; $i++) {
$username = "user$i";
$email = "user$i@example.com";
$password = "password123";
$values[] = "('$username', '$email', '$password')";
}
$sql = "INSERT INTO users (username, email, password) VALUES " . implode(', ', $values);
if ($conn->query($sql) === TRUE) {
echo "批量插入成功";
} else {
echo "插入失败: " . $conn->error;
}
$conn->close();
?>最佳实践
- 使用预处理语句:防止 SQL 注入攻击
- 数据验证:在插入前验证数据的有效性
- 错误处理:处理插入过程中的错误
- 事务处理:对于相关操作使用事务
- 批量插入:对于大量数据使用批量插入
- 密码加密:使用 password_hash() 加密密码
- 获取插入ID:使用 $conn->insert_id 获取刚插入记录的ID
练习
- 插入单条用户记录
- 插入多条用户记录
- 使用预处理语句插入数据
- 结合表单插入数据
- 使用事务插入相关数据
- 批量插入大量数据
