如何使用codeigniter将数据插入数据库中的表

时间:2015-01-28 14:04:37

标签: codeigniter object insert

我正在寻找一些我尚未在互联网上找到它的例子。我可以使用数组将数据插入数据库,但我不确定如何使用对象将数据添加到数据库。

你能告诉我一个基本上用对象插入数据的例子吗?

2 个答案:

答案 0 :(得分:2)

假设您有一个客户对象,并且您希望将详细信息插入到结算数据库中。在您的结算模式中:

    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;}

    }
控制器中的

检查插入是否为假

 if( $this->billing->insertFor( $customer ) == false ){

     $this->showerror($customer) ; } 

 else{ $this->nextMethodFor($customer) ;  } 

答案 1 :(得分:0)

您应该始终使用CodeIgniter用户指南。

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

相关问题