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

How can I insert data to a table in database using codeigniter

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

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

您应该始终从 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

假设您有一个客户对象,并且您想要将详细信息插入到帐单数据库中。在您的计费模型中:

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