php实现提交订单列表
PHP 实现提交订单列表
数据库设计
创建订单表 orders 存储订单信息,字段包括订单ID、用户ID、商品信息、订单状态、创建时间等。
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`product_info` text NOT NULL,
`status` tinyint(1) DEFAULT 0,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
订单提交表单
创建HTML表单收集订单信息,提交到PHP处理脚本。

<form action="submit_order.php" method="post">
<input type="text" name="product_name" placeholder="商品名称">
<input type="number" name="quantity" placeholder="数量">
<input type="text" name="address" placeholder="收货地址">
<button type="submit">提交订单</button>
</form>
订单处理脚本
创建 submit_order.php 处理表单提交,将订单数据存入数据库。
<?php
// 连接数据库
$conn = new mysqli('localhost', 'username', 'password', 'database');
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 获取表单数据
$product_name = $_POST['product_name'];
$quantity = $_POST['quantity'];
$address = $_POST['address'];
$user_id = 1; // 假设当前用户ID为1
// 准备SQL并绑定参数
$stmt = $conn->prepare("INSERT INTO orders (user_id, product_info, status) VALUES (?, ?, ?)");
$product_info = json_encode(['name' => $product_name, 'quantity' => $quantity, 'address' => $address]);
$status = 0; // 0表示待处理
$stmt->bind_param("isi", $user_id, $product_info, $status);
// 执行SQL
if ($stmt->execute()) {
echo "订单提交成功";
} else {
echo "错误: " . $stmt->error;
}
$stmt->close();
$conn->close();
?>
订单列表显示
创建 order_list.php 从数据库获取订单列表并显示。

<?php
// 连接数据库
$conn = new mysqli('localhost', 'username', 'password', 'database');
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 查询订单
$sql = "SELECT * FROM orders WHERE user_id = 1 ORDER BY created_at DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$product_info = json_decode($row['product_info'], true);
echo "订单ID: " . $row['id'] . "<br>";
echo "商品: " . $product_info['name'] . "<br>";
echo "数量: " . $product_info['quantity'] . "<br>";
echo "状态: " . ($row['status'] ? '已完成' : '处理中') . "<br><hr>";
}
} else {
echo "暂无订单";
}
$conn->close();
?>
安全注意事项
对用户输入进行验证和过滤,防止SQL注入。
$product_name = htmlspecialchars(strip_tags($_POST['product_name']));
$quantity = filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT);
$address = htmlspecialchars(strip_tags($_POST['address']));
性能优化
对于大量订单,实现分页功能。
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;
$sql = "SELECT * FROM orders WHERE user_id = 1 ORDER BY created_at DESC LIMIT $limit OFFSET $offset";






