【问题标题】:Store array and update record in database using codeigniter使用 codeigniter 在数据库中存储数组和更新记录
【发布时间】:2015-09-25 03:28:58
【问题描述】:

我正在存储动态数组以及更新数据库中的“max_quantity”表。问题是,当更新记录时,它会将所有数量值相加并从“最大数量表”的第一个值中减去。但我希望该数量数组减去它自己存在于数据库中的数量值。

这是我的代码

<?php $i=1; foreach($result as $row){
        ?>

  <td class="pr-right" style='width:130px; text-align: center; '>

                <input type="text" min="1" step="1"  name="quantity[]" step="1" class="container" value="" onfocus="this.value = '';" onblur=";" style="width: 60px" id="quantityT<?php echo $i;?>" onkeyup="CalculatePrice (<?php echo $i;?>,<?php echo $row->max_quantity; ?>)">
                <br>(Quantity Available = <?php echo $row->max_quantity; ?>)
            </td>

             <?php
        $i++;
} ?>

这是我在控制器中的代码

public function get_insert_order(){
   $quantity=$this->input->post('quantity');

   for($i=0; $i<count($ingredient); $i++){
    $data = array(
    "user_quantity" =>$quantity[$i],
    );
      $response =  $this->bulk_recipe->insert_bulk_order($data);
            $max = $this->db->query("select bulk_delivery.max_quantity from bulk_delivery")->result_array();

            foreach ($max as $rows) {
                $calc = $rows['max_quantity'];
                $calc = $calc - $quantity[$i];
            }


            $this->db->query("UPDATE bulk_delivery SET max_quantity =$calc");
}

这是我在模型中的代码

function insert_bulk_order($form_data)
{
    $this->db->insert('bulk_delivery_order',$form_data);


    if ($this->db->affected_rows() == '1')
    {
        return TRUE;
    }

    return FALSE;
}

这是更新前的前端视图。

这是更新后的前端

请指导我如何将每个数量分别减去其 max_quantity。

【问题讨论】:

    标签: php arrays database codeigniter


    【解决方案1】:

    这就是你要找的……!

    $this->db->set();
    

    此功能使您可以设置插入或更新的值。

    它可以用来代替将数据数组直接传递给插入或更新函数:

    $this->db->set('field', 'field+1', FALSE);
    $this->db->insert('mytable'); 
    // gives INSERT INTO mytable (field) VALUES (field+1)
    
    $this->db->set('field', 'field+1');
    $this->db->insert('mytable'); 
    // gives INSERT INTO mytable (field) VALUES ('field+1')
    

    https://ellislab.com/codeigniter/user-guide/database/active_record.html

    【讨论】:

      【解决方案2】:

      您的代码有几个错误,您从 db 中选择所有行并每次更新所有行。 你的代码应该是这样的......

      $max = $this->db->query("select bulk_delivery.max_quantity from bulk_delivery where some_id = $i")->row_array();
      
      $calc = $rows['max_quantity'];
      $calc = $calc - $quantity[$i];
      
      $this->db->query("UPDATE bulk_delivery SET max_quantity =$calc WHERE some_id = $i");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多