【问题标题】:Taking Array Post Data and INSERTING to sql将数组发布数据和插入到 sql
【发布时间】:2020-09-18 15:23:33
【问题描述】:

我正在尝试获取一个 $_POST 数据数组并使用 3 个插入语句将其插入到 mysql 中......以在表中创建 3 个新行。

表格:name 字段中的变量是创意工坊 ID 号。

        <div class="form-group row">
        <label for="make" class="col-sm-2 col-form-label">Appropriate</label>
        <div class="col-sm-4"><input type="text" name="appropriate[<?php echo $theassign?>]"  class="form-control" >
        </div>
    </div>
    <div class="form-group row">
        <label for="model" class="col-sm-2 col-form-label">Useful</label>
        <div class="col-sm-4"><input type="text" name="useful[<?php echo $theassign?>]"  class="form-control" >
        </div>
    </div>
    <div class="form-group row">
        <label for="serial" class="col-sm-2 col-form-label">understandable</label>
        <div class="col-sm-4"><input type="text" name="understandable[<?php echo $theassign?>]"  class="form-control" >
        </div>
    </div> 

最后的 mysql 语句将类似于以下内容,其中 $workshopid 来自数组中括号内的数字

INSERT INTO evaluation (workshopid, appropriate, useful, understandable) VALUES ($workshopid, $appropriate, $useful, $understandable)

INSERT INTO evaluation (workshopid, appropriate, useful, understandable) VALUES ($workshopid, $appropriate, $useful, $understandable)

INSERT INTO evaluation (workshopid, appropriate, useful, understandable) VALUES ($workshopid, $appropriate, $useful, $understandable)

目前,print_r($_POST); yields:

Array ( [appropriate] =&gt; Array ( [12] =&gt; 1 [4] =&gt; 2 [11] =&gt; 3 ) [useful] =&gt; Array ( [12] =&gt; 1 [4] =&gt; 2 [11] =&gt; 3 ) [understandable] =&gt; Array ( [12] =&gt; 1 [4] =&gt; 2 [11] =&gt; 3 ) [helpful] =&gt; Array ( [12] =&gt; 1 [4] =&gt; 2 [11] =&gt; 3 ) )

有人可以帮忙解决 foreach 循环吗?

这让我很接近

$keys = array_keys($_POST); 
for($i = 0; $i < count($_POST); $i++) { 
    echo $keys[$i] . "<br>"; 
    foreach($_POST[$keys[$i]] as $key => $value) { 
        echo $key . ":" . $value . "<br>"; 
    } 
    echo "<br>"; 
}

但我不想将“适当的”.. 组合在一起.. 我想将 12 组合在一起,因为那是 $workshopid。

appropriate
12:1
4:2
11:3

useful
12:1
4:2
11:3

understandable
12:1
4:2
11:3

helpful
12:1
4:2
11:3

【问题讨论】:

    标签: php mysql arrays


    【解决方案1】:

    考虑到值总是一个数字,我会做这样的事情:

    $inserts = array();
    foreach($_POST['appropriate'] as $workshipid => $appropriate){
        $appropriate = (int) $appropriate;
        $useful = (int) $_POST['useful'][$workshipid];
        $understandable = (int) $_POST['understandable'][$workshipid];
        $inserts[] = "($workshopid, $appropriate, $useful, $understandable)";
    }
    
    //Query:
    if($inserts){
        $query = "INSERT INTO evaluation (workshopid, appropriate, useful, understandable) VALUES " . implode(',', $inserts);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-01
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 2014-07-08
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多