我用dbforge创建了数据库设置模型,并通过控制器调用它来设置数据库。但问题是当我从localhost运行url时,它会在调用“未知数据库'loginproject'”的数据库错误时出错。注意到我在config>中设置了数据库database.php 'database'=> 'loginproject', 即可。如果我将它删除,它将不会显示错误。但我想留在那里,因为以后需要在项目中。如何设置它留在那里进行数据库设置。我的代码如下。
Welcome.php- controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this-> home();
}
public function home()
{
$data['title'] = 'This is title';
$this -> load -> model('setup_model');
$this -> setup_model -> createDatabase();
$this -> load -> view('welcome_message');
}
}
Setup_model.php-型号:
<?php
class setup_model extends CI_Model
{
public function __construct() {
}
public function createDatabase()
{
$this->load->dbutil();
$this->load->dbforge();
if (!$this->dbutil->database_exists('loginproject'))
{
$this->dbforge->create_database('loginproject');
$this->db->query('use loginproject');
$fields = array(
'user_id' => array(
'type' => 'int',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true
),
'username' => array(
'type' => 'varchar',
'constraint' => 230,
),
'email' => array(
'type' => 'varchar',
'constraint' => 250,
),
'password' => array(
'type' => 'varchar',
'constraint' => 255,
),
'created_date' => array(
'type' => 'date',
),
'phone' => array(
'type' => 'varchar',
'constraint' => 255,
),
);
$this -> dbforge -> add_field($fields);
$this -> dbforge -> add_key('user_id', true);
$this -> dbforge -> create_table('users');
echo "Setup Done Succesfully";
}
}
}
答案 0 :(得分:0)
手动创建数据库并连接config / database.php
然后在 createDatabase()
public function createDatabase(){
$this->load->dbutil();
$this->load->dbforge();
if (!$this->dbutil->database_exists('loginproject'))
{
$this->dbforge->create_database('loginproject');
}
$this->db->query('use loginproject');
$fields = array(
'user_id' => array(
'type' => 'int',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true
),
'username' => array(
'type' => 'varchar',
'constraint' => 230,
),
'email' => array(
'type' => 'varchar',
'constraint' => 250,
),
'password' => array(
'type' => 'varchar',
'constraint' => 255,
),
'created_date' => array(
'type' => 'date',
),
'phone' => array(
'type' => 'varchar',
'constraint' => 255,
),
);
$this -> dbforge -> add_field($fields);
$this -> dbforge -> add_key('user_id', true);
$this -> dbforge -> create_table('users');
echo "Setup Done Succesfully";
}