簡體   English   中英

無法將針對id的多個數據插入到mySQL表中的多個字段中?

[英]Can't insert multiple data against an id into multiple fields in a table in mySQL?

場景:我的PHP頁面中有一個表單,將數據插入到mySQL數據庫中。

假設,對於每種類型的T恤,都有顏色變化,尺寸變化和其他類似的。 所以在我的數據庫中,我想存儲這樣的數據:

---+------+--------+---------
    id | p_id | colors | random
    ---+------+--------+---------
     1 |   1  |   red  |   400
     2 |   1  |  green |   400
     3 |   1  | orange |   400
     4 |   2  |  green |   200
     5 |   2  |  blue  |   200
    ---+------+--------+---------

我正在使用這樣的表格:

Product id     | color                             | random
    ---------------+-----------------------------------+----------
    [Product 1 [v] | [+]Red [+]Green [+]Orange [o]Blue | [    400]
    ---------------+-----------------------------------+----------

圖例: [+]和[o]是復選框, [v]是下拉菜單, [ ]是文本框。

但每次我發布表單時,它都會像這樣插入:

---+------+--------+---------
    id | p_id | colors | random
    ---+------+--------+---------
     1 |   1  |   red  |   400
     2 |   1  |  green |   
     3 |   1  | orange |   
    ---+------+--------+---------

如何在所有三行中插入“隨機”數字?

我想我理解你的問題並發布這個解決方案。你可以在一個數組中的顏色復選框字段,如:

<input type="checkbox" name="color[]" value="Red"/>Red
<input type="checkbox" name="color[]" value="Green"/>Green
<input type="checkbox" name="color[]" value="Orange"/>Orange
<input type="checkbox" name="color[]" value="Blue"/>Blue

現在,如果您發布表單,您將獲得一系列顏色,只選中復選框。 例如,如果您選中了紅色和橙色,則數組將如下所示:

Array ([color] => Array ( [0] => Red [1] => Orange ))

現在,您可以在此處運行循環以在數據庫中插入值。

<?php
    let,$random=$_POST['random']; 
        $p_id=$_POST['p_id'];
        $colors=$_POST['color'];

    foreach($colors as $each)
    {
        INSERT INTO `shirts`(`p_id`, `colors`, `random`) VALUES ($p_id, $each, $random);
    }
?> 

希望它會幫助你。如果你遇到任何問題,請問我。

如果您可以發布用於插入數據的MySQL語句,那將非常有用。 規范的方式是:

INSERT INTO `shirts`(`p_id`, `colors`, `random`) VALUES (1, 'red', 400), (1, 'green', 400), (1, 'orange', 400);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM