如果在db表中发现了什么,php/mysql将更新它


If something is found in the db table, php/mysql will update it

我正试图让下面的工作正确。我有其他工作正常,但我在if部分遇到了问题。它所做的是删除这行并在hottest_cat行中插入0。它应该插入$dd的值。知道我哪里做错了吗?

public function change_category() {
        $dd = $this->input->post('dd');
        $sql = $this->db->get('default_hottest_cat');
        if ($sql->num_rows() > 0) {
            $row = $sql->row(); 
                $old = $row->hottest_cat;
                // Stuff is found in this table. Needs to be deleted first, then inserted.
                $this->db->delete('default_hottest_cat', array('hottest_cat' => $old));
                $this->db->insert('default_hottest_cat', array('hottest_cat' => $dd));
        } else {
            // Nothing is found in this table. Needs only to be inserted.
            $this->db->insert('default_hottest_cat', array('hottest_cat' => $dd));
        }
    }

你的问题与我回答过的一个问题非常相似。请查看更多信息如何检查id是否已经存在- codeigniter

逻辑是

1.Select "the database table" with the value you had posted.(search)
2.Check the count of result_row(if found >0 , if not found =0)
3.If not found  'insert', if found 'update',( in your case delete)

模型
<?php
    class Cars_model extends CI_Model
    {   
        function __construct()
        {
            parent:: __construct();
            $this->load->database();
        }
         function check()
         {
            $query=null; //emptying in case 
            $dd= $_POST['dd'];    //getting from post value
            $query = $this->db->get_where('default_hottest_cat', array('dd' => $dd)); ၊၊၊။။//making selection
            $count= $query->num_rows();    //counting result from query
        if ($count === 0)  // data is not present
        {  
               $data = array(
                 'dd' => $dd
            );
           $this->db->insert('default_hottest_cat', $data); 
        }
           else //data is present
          {
               $this->db->delete('default_hottest_cat', array('dd'=>$dd));
           }
         }     
    }
?>