Php CodeIgniter-将数据保存在模型中

Php CodeIgniter-将数据保存在模型中,php,codeigniter,model,static,Php,Codeigniter,Model,Static,基本上,我所拥有的是: class Database extends CI_Model { function __construct() { parent::__construct(); } function connect($connection_infos) { $db = @new mysqli($connection_infos['host'], $connection_infos['username'],

基本上,我所拥有的是:

class Database extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    function connect($connection_infos)
    {
        $db = @new mysqli($connection_infos['host'], $connection_infos['username'],
                $connection_infos['password'], $connection_infos['database']);
        if (mysqli_connect_errno())
            return FALSE;
        else
            return TRUE;
    }
}
此模型加载在控制器的函数中:

class Management extends CI_Controller
{

    static $dbs = array(
                'ref' => array(
                    'connected' => FALSE,
                ),
                'dest' => array(
                    'connected' => FALSE,
                )
            );

    function connection()
    {
        $this->load->library('form_validation');
        $data = array();

        $this->form_validation->set_rules('host', 'Hostname', 'required');
        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('database', 'Database', 'required');
        if (!$this->form_validation->run()) {
            $data['dbs'] = self::$dbs;
        } else {
            $this->load->model('database'); // Here I load the model
            $connection_infos = array(
                    'host' => $this->input->post('host'),
                    'username' => $this->input->post('username'),
                    'password' => $this->input->post('password'),
                    'database' => $this->input->post('database'),
                );
            if ($this->database->connect($connection_infos)) {
                self::$dbs['ref']['connected'] = TRUE;
                $data['dbs'] = self::$dbs;
            }
        }
        $this->load->view('dashboard', $data);
    }
}
以下是我所做的:

在我视图中的表单验证中,我从控制器调用函数
connection
。此函数加载
数据库
模型,并调用模型的
连接
函数

我的问题是:如果我想让我的模型中的其他函数发出其他请求,我每次都会被迫打开一个连接吗?如果是,如何“存储”连接凭据


谢谢

根据我所看到的,您需要浏览一下CI文档,并阅读大量有关CI的信息

除了教程中介绍的基本语法/语义之外,名为“Database”的模型是不合逻辑的,不是一个很好的命名选择。在CodeIgniter的范围内,您应该尝试使模型仅与一个数据库表相关

至于实际的数据库连接,它在CI_模型类中作为成员对象,
$db
自动处理。我建议在CI上和中阅读文档


因此,当您正确设置所有内容后,加载一个正确编码的模型将为您提供一个模型内的自动数据库连接,该连接可以在任何时候重新使用。

您知道Codeigniter确实有一个数据库帮助器库,对吗?其中,您可以创建一个自定义模型,其中包含您可能希望重用的所有函数和请求,而不必担心创建您自己的数据库类,或者在需要时担心它的连接等。我有一个问题,您为什么要使用Codeignitor?@chris当然是,但我想动态连接到db,这取决于用户在表单中放置的内容。@它是一个轻巧而强大的框架,易于学习和使用。这是一次性设置的吗?就像这个应用程序的开头一样,你可以
打开
数据库.php
配置文件并直接设置,其他方法你需要稍微调整一下DB类当前连接是从
配置
数组读取,而不是从DB读取设置并使用它。我知道所有这些东西,但在这里,我想使用用户在表单中输入的凭据动态连接到db。