2014-01-15 32 views
1

我已經在codeigniter驅動程序的幫助下將我的php web應用程序連接到mongodb。在codeigniter中插入函數mongodb

現在我正在使用mongoo_db類將集合插入到默認數據庫db_name中。

我的文件的源代碼,

ghy.php

<?php 
/** 
* @author 
* @copyright 2014 
*/ 
class ghy 
{ 
    public $id; 
    public $name; 
    public function insert($collection = "", $data = array()) { 
     if(empty($collection)) 
      show_error("No Mongo collection selected to insert into", 500); 
     if(count($data) == 0 || !is_array($data)) 
      show_error("Nothing to insert into Mongo collection or insert is not an array", 500); 
     try { 
      $this->db->{$collection}->insert($insert, array('safe' => TRUE)); 
      if(isset($insert['_id'])) 
       return($insert['_id']); 
      else 
       return(FALSE); 
     } catch(MongoCursorException $e) { 
      show_error("Insert of data into MongoDB failed: {$e->getMessage()}", 500); 
     } 
     $use=$this->mongo_db->insert('foo', $data = array('4','hgfh')); 
     var_dump(); 
     } 
    } 
?> 

的問題是,我沒有得到我的瀏覽器的任何輸出。

任何人都可以解釋我在哪裏我會出錯?最早的答覆將受到高度讚賞。

三江源

+0

嘗試'echo'你的輸出,即'回聲var_dump($ use)' – Renier

+0

@Renier我試過沒有顯示任何東西。可以告訴我如何在php程序中使用活動的驅動程序庫。如何使用連接字符串建立與mongodb的連接 – user3189732

+0

其中'ghy.php'位於何處?即'ci/models/ghy.php'? – Renier

回答

0

我不知道爲什麼你的類不能正常工作,但得到的MongoDB的和笨是如何一起看看這answer的理解。

answer回答你如何建立的MongoDB來連接問題:

配置/ mongo.php

$config['mongo_server'] = null; 
$config['mongo_dbname'] = 'mydb'; 

庫/ Mongo.php

class CI_Mongo extends Mongo 
{ 
    var $db; 

    function CI_Mongo() 
    { 
     // Fetch CodeIgniter instance 
     $ci = get_instance(); 
     // Load Mongo configuration file 
     $ci->load->config('mongo'); 

     // Fetch Mongo server and database configuration 
     $server = $ci->config->item('mongo_server'); 
     $dbname = $ci->config->item('mongo_dbname'); 

     // Initialise Mongo 
     if ($server) 
     { 
      parent::__construct($server); 
     } 
     else 
     { 
      parent::__construct(); 
     } 
     $this->db = $this->$dbname; 
    } 
} 

和一個樣本控制器

控制器/ posts.php

class Posts extends Controller 
{ 
    function Posts() 
    { 
     parent::Controller(); 
    } 

    function index() 
    { 
     $posts = $this->mongo->db->posts->find(); 

     foreach ($posts as $id => $post) 
     { 
      var_dump($id); 
      var_dump($post); 
     } 
    } 

    function create() 
    { 
     $post = array('title' => 'Test post'); 
     $this->mongo->db->posts->insert($post); 
     var_dump($post); 
    } 
} 

question如上回答:

MongoDB是笨社區內很好的支持,需要在時間和潛水:對

我希望這可以幫助你得到你的笨(MongoDB的)項目工作

+0

我已經看到this.but但我不明白在哪裏實現功能..您給出的答案是關於驅動程序 – user3189732

+0

我的答案是關於如何使用MongoDB庫,並且您在上面的註釋中提到了「如何使用活動驅動程序庫」,您只需要將此代碼在您的項目中實現,並且您將能夠連接到你的MongoDB數據庫。你在代碼上面的文件中實現它,即'config/mongo.php'意味着你的'config'文件夾中有一個名爲'mongo.php'的文件,如果它不存在,那麼創建它。 – Renier

+0

謝謝你,我已經這樣做了。現在我正在使用我的php代碼,它不能連接到數據庫 – user3189732