2016-01-19 70 views
2

爲什麼插入操作不起作用,我的數據庫不接受我試圖插入的數據。我已經使用autoload配置來加載數據庫和New_model類。使用codeigniter框架將數據插入數據庫不起作用

New_controller.php

<?php 
if (! defined('BASEPATH')) exit('No direct script access allowed'); 

class New_controller extends CI_Controller { 

    /** 
    * Index Page for this controller. 
    * 
    * Maps to the following URL 
    *  http://example.com/index.php/welcome 
    * - or - 
    *  http://example.com/index.php/welcome/index 
    * - or - 
    * Since this controller is set as the default controller in 
    * config/routes.php, it's displayed at http://example.com/ 
    * 
    * So any other public methods not prefixed with an underscore will 
    * map to /index.php/welcome/<method_name> 
    * @see http://codeigniter.com/user_guide/general/urls.html 
    */ 
    public function index($id) 
    { 
     //$this->load->model("New_model"); 
     $data["posts"]=$this->New_model->database($id); 

     $this->load->view("New_view",$data); 
    } 

    public function insert_post() 
    { 
      $this->New_model->create([ 
      'post_title'=>'health is wealth', 
      'post_description'=>'as we know health is a gift of nature we should take care of our self', 
      'post_author'=>'krishna', 
      'post_date'=>'2016-01-19' 
      ]); 
    } 
} 
?> 

我已經使用自動加載配置加載New_model class.everything似乎是不錯,但我的插入操作不工作

New_model.php 
<?php 

class New_model extends CI_Model { 

    public function database($id) 
    { 
     //$this->load->database(); 
     //$sql=$this->db->query("SELECT * FROM posts"); 

     $this->db->where("id",$id); 
     $sql=$this->db->get("posts"); 

     $result=$sql->result_array(); 

     return $result; 
    } 
    public function create($data) 
    { 
     $this->db->insert("posts",$data); 
    } 

} 
?> 
+0

你讓你的'create'函數中的數組嘗試使用'數據print_r' –

回答

1

試試這個

將其更改爲

$this->New_model->create([ 
      'post_title'=>'health is wealth', 
      'post_description'=>'as we know health is a gift of nature we should take care of our self', 
      'post_author'=>'krishna', 
      'post_date'=>'2016-01-19' 
      ]); 

$data = array(
     'post_title'=>'health is wealth', 
     'post_description'=>'as we know health is a gift of nature we should take care of our self', 
     'post_author'=>'krishna', 
     'post_date'=>'2016-01-19' 
    ); 

$this->New_model->create($data); 
+0

只需幾秒就打敗我! – Saty

+0

@Saty thanx buddy –

1

插入,你必須創建數組作爲

function insert_post() { 
    $datanew = array(
     'post_title' => 'health is wealth', 
     'post_description' => 'as we know health is a gift of nature we should take care of our self', 
     'post_author' => 'krishna', 
     'post_date' => '2016-01-19' 
    ); 
    $this->New_model->create($datanew); 
} 

http://www.codeigniter.com/userguide2/database/queries.html

+0

它仍然不接受db中的數據? –

+0

檢查更新!你有沒有在autoconfig.php文件中加載你的模型? – Saty

+0

是的,我已經加載該模型類 –

相關問題