【问题标题】:Codeigniter update specific valueCodeigniter 更新特定值
【发布时间】:2017-07-27 18:06:16
【问题描述】:

我在 MySql 数据库中有一个表,其中包含 post_id 、 post_number 、 post_like

我在codeigniter中使用MVC从mysql表中获取所有数据并显示在页面上(这部分已经完成)

我需要为每个 post_id 添加一个按钮,为 mysql 表中的 post_like 添加 +1,对应于 post_id。

所以如果我点击 post_id 7 的 +1 按钮,post_like 应该只会增加 post_id 7。

这是我目前所拥有的!

view_page.php

     <?php foreach($members as $value): ?>
        <tr>
          <td><?php echo $value['post_id']; ?></td>
          <td><?php echo $value['post_like']; ?></td>
          <td> <a href="plusone/<?php echo $value['post_id']; ?>">Add +1</a></td>
        </tr>
      <?php endforeach; ?>

controller_page.php

   <?php


    function plusone($post_id){

       $this->load->model('model_page');
       $this->model_page->data_addition($post_id);
       redirect('controller_page/viewdata');

   }

   ?>

Model_page.php

        <?php

    function data_addition($post_id){

       //trying to add 1 the post_like and update it in the db
        $add_one_to_data = $post_like+ 1;

        $data = array(
           'post_like' => $add_one_to_data +1 
        );

        $this->db->where('post_id', $post_id);
        $this->db->update('post_tbl', $data); 

    }

   ?>

请不要嘲笑我在数组上面添加的$add_one_to_data,我不知道还能做什么

提前致谢

【问题讨论】:

    标签: php mysql codeigniter


    【解决方案1】:

    你需要先得到 ifno,比如:

    function data_addition($post_id){
           $post_like = $this->db->get_where('post_tbl', array('post_id' => $post_id))->row();
    
           //trying to add 1 the post_like and update it in the db
            $add_one_to_data = (int) $post_like->post_like + 1;
    
            $data = array(
               'post_like' => $add_one_to_data +1 
            );
    
            $this->db->where('post_id', $post_id);
            $this->db->update('post_tbl', $data); 
    
        }
    

    【讨论】:

    • 非常感谢您的帮助。我意识到数组内不需要第二个 $add_one_to_data +1,因为它已经在上面完成了:)
    【解决方案2】:

    用这个替换你的 data_addition 函数

    function data_addition($post_id){  
        $this->db->set('post_like', 'post_like+1', FALSE);
        $this->db->where('post_id', $post_id);
        $this->db->update('post_tbl');
    }
    

    【讨论】:

    • 谢谢,很干净
    • 如果有帮助请投票
    • 不错且高效的解决方案。我将发布相同的解决方案。 1up 从我这边。
    • @ankitsuthar 感谢支持
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多