用户在CodeIgniter

时间:2016-08-05 10:36:28

标签: php codeigniter pdo

我是Codeigniter的新手并尝试连接到用户定义的动态数据库,就像我们通常用PHP做的那样。

目前,我可以使用用户指南中的设置提示连接到数据库,并尝试访问它,如..

class ModelTest extends CI_Model
{
    public function getdata()
    {
        $this->load->database();
        $q=$this->db->query("SELECT * FROM users");
        return $q->result();

    }

}

现在我想使用用户定义的数据库访问它,而不是我们正常使用的默认值..

class Database{

    // specify your own database credentials
    private $host = 'mysql:host=localhost;dbname=satudent_enrollement';
    private $username = 'root';
    private $password = '';
    public $conn;

    // get the database connection
    public function getConnection(){

        $this->conn = null;

        try{
            $this->conn = new PDO($this->host , $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}
  

我想要的:使用用户定义的数据库连接数据库而不是默认数据库。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

根据Codeigniter User Guide,您可以通过$this->load->model的第三个参数手动传递数据库连接设置:

$config['hostname'] = "mysql:host=localhost";
$config['username'] = "root";
$config['password'] = "XXX";
$config['database'] = "satudent_enrollement";
$config['dbdriver'] = "pdo";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;

$this->load->model('ModelTest', '', $config);

// or as gorelative notes, to access multiple databases:

$DB2 = $this->load->database($config, TRUE);

我希望它对你有用!!

答案 1 :(得分:0)

在database.php中使用以下设置为2.x版本中的PDO

$db['default']['hostname'] = 'mysql:host=localhost';
$db['default']['dbdriver'] = 'pdo';
$db['default']['database'] = 'satudent_enrollement';

希望有所帮助

相关问题