簡體   English   中英

Codeigniter 4 - 更新多行

[英]Codeigniter 4 - update multiple rows

我想立即更新與我的圖像相關的一些信息,但無法弄清楚我面臨的問題。

這是我的看法:

<form action="my_controller_path" method="post">
    <?php foreach ($my_images as $mi) { ?>
        <div>
            <div class="img">
                <img src="<?php echo base_url($mi->image_path); ?>" />
            </div>

        <div class="other-infos">
            <div class="title">Image Text:</div>

                <input type="text" class="form-input" name="image_text[]" value="<?php echo $mi->image_info;?>"/>

            <div class="title">Order</div>
               <input type="number" value='<?php echo $mi->image_order; ?>' name="image_order[]">

            <div class="title">Color</div> 
                <input type="text" value='<?php echo $mi->image_color; ?>' name="image_color[]">

           <input type="hidden" name="image_id[]" class="image_id" value="<?php echo $mi->image_id;?>">
    </div>
<?php } ?>

<button>Update</button>

</form>

這是我的 Controller:

    public function update_image_infos(){
  
   $image_id = $this->request->getVar('image_id');
    
   $number = count($image_id);

    $db      = \Config\Database::connect();
    $builder = $db->table('product_images');

$data  = [];
    
        $image_text = $this->request->getVar('image_text');
        $image_color = $this->request->getVar('image_color');
        $image_order = $this->request->getVar('image_order');
        
        for($i=0; $i<$number; $i++){
            
        $data[] = [
                'image_text' => $image_text[$i],
                'image_color' => $image_color[$i],
                'image_order' => $image_order[$i]
            ];
    }

//print_r($data);

$builder->where('image_id',$image_id);
$builder->update($data);

etc. etc.   return redirect()->to($_SERVER['HTTP_REFERER']);

}

我的 print_r 將數組返回給我,但無法更新。 我有錯誤:

mysqli_sql_exception #1064 您的 SQL 語法有錯誤; 檢查與您的 MariaDB 服務器版本相對應的手冊,以了解在 '0 = ('Info A','green','2'), 1 = ('Other Info','brown','1') 附近使用的正確語法) WHERE `image_id...' 在第 1 行

我的問題的答案如下:感謝@mail2bapi 的一半解決方案:

for($i=0; $i<$number; $i++){

$data = [
        'image_text' => $image_text[$i],
        'image_color' => $image_color[$i],
        'image_order' => $image_order[$i]
    ];

$builder->where('image_id',$image_id[$i]);  //this line is the answer
$builder->update($data);

}

$builder->update() 與一維數組一起使用,您的 $data 數組是多維的。 所以你需要在 for 循環中使用它;

for($i=0; $i<$number; $i++){
    
    $data = [
            'image_text' => $image_text[$i],
            'image_color' => $image_color[$i],
            'image_order' => $image_order[$i]
        ];

    $builder->where('image_id',$image_id);
    $builder->update($data);
}

您也可以使用 $builder->updateBatch() 但您需要重新構建 $data 數組。 看看文檔

暫無
暫無

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

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