2017-06-21 50 views
0

我是codeigniter的新手,請不要給予負面的費率。我爲登錄註冊項目創建了一個數據庫和用戶表模型文件。型號代碼是在這裏,如何在Codeigniter中加載主頁時跳過數據庫文件或模型文件?

<?php 

    class setup_model extends CI_Model 

    { 

     public function __construct() { 

     } 

     public function createDatabase() 

     { 

      $this->load->dbforge(); 


      if ($this->dbforge->create_database('loginproject5')) 

      $this->db->query('use loginproject5'); 


      $fields = array(

       'user_id' => array(

        'type' => 'int', 
        'constraint' => 11, 
        'unsigned' => true, 
        'auto_increment' => true 

       ), 
       'username' => array(

        'type' => 'varchar', 
        'constraint' => 30, 

       ), 

       'password' => array(

       'type' => 'varchar', 
        'constraint' => 30, 


       ), 

       'email' => array(

        'type' => 'varchar', 
        'constraint' => 50, 
       ) 


      ); 


      $this -> dbforge -> add_field($fields); 

      $this -> dbforge -> add_key('user_id', true); 

      $this -> dbforge -> create_table('users'); 


      echo "Setup Done Succesfully"; 


     } 


    } 

我想設置數據庫首先從項目文件夾。所以我設定了這個。現在一邊加載主文件,一邊數據庫設置。但是在第二次加載時會給出錯誤,因爲數據庫已經設置好了。現在我想在加載主頁時第二次跳過數據庫設置。如何設置條件以擺脫它或如何跳過它。我的控制器代碼是在這裏

class Welcome extends CI_Controller { 

    public function index() 
    { 
     $this-> home(); 
    } 


    public function home() 

{ 

$data['title'] = 'This is title'; 


$data['page_header'] = "Login Register Program"; 

$this -> load -> model('setup_model'); 

$this -> setup_model -> createDatabase(); 

$this -> load -> view('view_home', $data); 


} 


} 

回答

0

在你的CreateDatabase在模型()函數, 如果包裹內的條件都如下面的代碼樣本。這個create_database()將檢查你的數據庫是否存在,並執行後面的代碼。你只是錯過了。

if ($this->dbforge->create_database('loginproject5')) 
{ 
.... 
} 

編輯

因爲,它無法正常運行,你可以,如果數據庫存在,或檢查不

public function createDatabase() 
{ 
$this->load->dbutil(); 
$this->load->dbforge(); 
if (!$this->dbutil->database_exists('loginproject5')) 
{ 
    your code... 
    } 
} 
+0

好吧,我正在爲 –

+0

它不工作,同樣的錯誤 –

+0

只是增加了一些編輯 – prab

0

檢查數據庫連接第一

if($this->load->database() === FALSE){//no database //your code here//} 
else{ 
redirect('welcome'); 
} 
+0

我有檢查這個代碼同樣的事情顯示,數據庫退出的錯誤 –

+0

確定,現在我正在檢查 –

+0

哪裏必須給這個代碼?,我仍然錯誤 –

相關問題