duanlie4621 2016-11-10 17:54
浏览 32
已采纳

使用for()更新mysql数据库中的多行

I am trying to update multiple rows in a database. I have the total number of rows in my table counted and bound to a variable:

$result = '32'

I then attempt to query each row:

for ($x = 0; $x <= $result; $x++)
{
    if ($update = $db -> prepare("UPDATE substrates SET substrate_name = ?, substrate_desc = ?, substrate_base = ?, substrate_tax = ? WHERE substrate_id = ?"))
    {
        $substrate_name = $_POST['substrate_name'];
        $substrate_desc = $_POST['substrate_desc'];
        $substrate_base = $_POST['substrate_base'];
        $substrate_tax  = $_POST['substrate_tax'];
        $substrate_id   = $x;
        $update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
        if ($update -> execute() == true) {
            // Success stuff...
        } 
        else {
            // Error stuff...
        }
        $update -> close();
    }
}

My problem is when I run this script, each row in the table is filled with the last row edited. For example:

AAA | Aaaaa | 1.00 | 6.35
BBB | Bbbbb | 2.00 | 6.35
CCC | Ccccc | 3.00 | 6.35

Becomes:

CCC | Ccccc | 3.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
CCC | Ccccc | 3.00 | 6.35

How can I fix this script so it will update each row individually?

  • 写回答

2条回答 默认 最新

  • douyan8027 2016-11-10 18:36
    关注

    I changed the "name" fields in my form to include the substrate's ID:

    <input name="substrate_name_'.$substrate_id.'" />

    Then did the same for the update query (where the id is defined by the loop, $x):

    $substrate_name = $_POST['substrate_name_'.$x];
    $substrate_desc = $_POST['substrate_desc_'.$x];
    $substrate_base = $_POST['substrate_base_'.$x];
    $substrate_tax  = $_POST['substrate_tax_'.$x];
    $substrate_id   = $x;
    $update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
    

    And this gave me the desired result. Thanks to Rimon Khan for the idea and to everyone who commented.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器