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条)

报告相同问题?

悬赏问题

  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款