How does PHP handle the two-dimensional display and submission of colors and sizes in product management?
P粉529965851
P粉529965851 2023-06-12 12:01:22
0
1
520

Dear friends, I recently encountered a problem with the color and size attributes of a product. For example, a product has two colors and three sizes.

Product A has a color design [black, white] and a size design [ S, M, L】

I want to click on the product list to go to the product details page, enter the quantity of each sku ordered, and then save and submit to the database. As shown below, can you give me some ideas? The color and size of each product are not fixed. The color and size information are retrieved from the database and displayed in an untabled header.

1.png

P粉529965851
P粉529965851

reply all(1)
WBOY
<table>
<thead>
<tr>
<th>商品名称</th>
<?php
// 从数据库中获取颜色信息
$colors = ['黑色', '白色'];

// 从数据库中获取尺码信息
$sizes = ['S', 'M', 'L'];

// 动态生成表头
foreach ($colors as $color) {
foreach ($sizes as $size) {
echo "<th>{$color} - {$size}</th>";
}
}
?>
</tr>
</thead>
<tbody>
<!-- 商品列表数据 -->
</tbody>
</table>

Use the `<input>` tag to create an input box, and use the `name` attribute to identify different SKUs. For example,

<tbody>
<?php
// 从数据库中获取商品列表数据
$products = [
['name' => '商品A', 'sku' => 'A001'],
['name' => '商品B', 'sku' => 'B001'],
// 其他商品数据...
];

// 遍历商品列表
foreach ($products as $product) {
echo "<tr>";
echo "<td>{$product['name']}</td>";

// 为每个SKU创建输入框
foreach ($colors as $color) {
foreach ($sizes as $size) {
$sku = "{$product['sku']}_{$color}_{$size}";
echo "<td><input type='number' name='{$sku}'></td>";
}
}

echo "</tr>";
}
?>
</tbody>

uses PHP to process form data and save it to the database. You can use the `$_POST` superglobal variable to get the form data and insert it into the database using SQL statements like

<?php
// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 连接数据库
$conn = new mysqli('localhost', 'username', 'password', 'database');

// 检查连接是否成功
if ($conn->connect_error) {
die('数据库连接失败:' . $conn->connect_error);
}

// 遍历表单数据
foreach ($_POST as $sku => $quantity) {
// 将SKU拆分为颜色和尺码
$parts = explode('_', $sku);
$color = $parts[1];
$size = $parts[2];

// 使用SQL语句将数据插入数据库
$sql = "INSERT INTO orders (sku, color, size, quantity) VALUES ('$sku', '$color', '$size', '$quantity')";
$result = $conn->query($sql);

// 检查插入是否成功
if (!$result) {
echo "插入数据失败:{$conn->error}";
}
}

// 关闭数据库连接
$conn->close();
}
?>

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!