Domanda

I am new code igniter and I follow through video tutorial create the initial code however, I am having trouble updating records.

Here is the code

Class MY_Model extends CI_Model {

const DB_TABLE = "abstract";
const DB_TABLE_PK = "abstract";

public function __construct()
{
    $this->load->database(); 
}


private function insert()
{
    $this->db->insert($this::DB_TABLE, $this);
    $this->{$this::DB_TABLE_PK} = $this->db->insert_id();
}


private function update()
{
    $this->db->update($this::DB_TABLE, $this, $this::DB_TABLE_PK);        
}

public function save()
{
    if(isset($this->{$this::DB_TABLE_PK}))
    {
        echo "inserting record";
        $this->update();
    }
    else
    {
        echo "updating record";
        $this->insert();
    }
}

}

Class Publication extends MY_Model {

const DB_TABLE = "publication";
const DB_TABLE_PK = "publication_id";


public $publication_id;
public $publication_name;

}

class Magazine extends CI_Controller {

public function db_update_publication_record()

{
    $this->load->model('Publication');
    $this->Publication->publication_id = 2;
    $this->Publication->publication_name = "update record -- it worked";
    $this->Publication->save();
    echo "<tt><pre>".  var_export($this->Publication, TRUE)."</pre></tt>";
}

}


when I try to update it doesn't find the DB_TABLE_PK and attempts to insert, how can I set the primary key in my model to I can update the record.

Please help

È stato utile?

Soluzione

You have to put an array or a where string in your 3rd paramater in :

$this->db->update($table, $update, $where); 

Something like :

$this->db->update($this::DB_TABLE, $this, array($this::DB_TABLE_PK => $this->{$this::DB_TABLE_PK})));  

But I am not sure "$this" in 2nd parameter works ?

Altri suggerimenti

This is an error in Lynda tutorial "Up and Running with PHP CodeIgniter". I ran into the same issue, but found that the documentation required an array as third argument for update - the tutorial just passes the name of the PK, so in fact it creates an SQL query "... UPDATE ... WHERE PK=NULL", which doesn't throw an error, but rather has the result of affecting 0 rows. The above answer by Vincent correctly shows how this function needs to coded.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top