2013-04-22 61 views
0

我想讓下面的工作正常。我有其他工作正常,但我遇到了問題,如果部分。它所做的是刪除行並將0插入hottest_cat行。它應該插入從$dd的值。任何想法,我做錯了什麼?如果在db表中發現了某些東西,php/mysql會更新它

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)); 
     } 
    } 
+2

爲什麼插入行註釋掉? – 2013-04-22 19:53:26

+0

因爲我在調試它。 – 2013-04-22 19:56:07

+0

我改變了它.... – 2013-04-22 19:56:49

回答

0

您的問題與我回答的問題非常相似。 請查看此獲取更多信息 How to check if id already exists - 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)); 
      } 
     }  
    } 

?> 
相關問題