Reputation: 59
I am looking for some examples I haven't found it yet on the internet. I can insert data to database with array but I am not sure about how to add data to database with objects.
Could you show me an example inserting data basically with object?
Upvotes: 0
Views: 1588
Reputation: 1823
You should always start with the CodeIgniter User guide.
class Myclass {
var $title = 'My Title';
var $content = 'My Content';
var $date = 'My Date';
}
$object = new Myclass;
$this->db->insert('mytable', $object);
// Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')
https://www.codeigniter.com/userguide2/database/active_record.html#insert
Upvotes: 0
Reputation: 3148
lets say you have an customer object and you want to insert the details into a billing database. in your billing model:
function insertFor( $customer ) {
// Create the data structure
$billing = array(
'first' => $customer->first,
'last' => $customer->last,
'address' => $customer->address,
'address2' => $customer->address2,
'city' => $customer->city,
'state' => $customer->state,
'zip' => $customer->zip,
// you can also use other things like helper functions you have created
'inserttime' => returnMicroDate(),
// php magic constants
'whatsmyname' => __FUNCTION__
);
// insert the array into billing table
$this->db->insert( 'billingtable', $billing );
// confirm that it inserted correctly
if ( $this->db->affected_rows() == '1' ) {
return true ; }
//return false if there was an error
else {return FALSE;}
}
in your controller check if the insert came back as false
if( $this->billing->insertFor( $customer ) == false ){
$this->showerror($customer) ; }
else{ $this->nextMethodFor($customer) ; }
Upvotes: 2