我是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;
}
}
我想要什么:使用用户定义的数据库而非默认数据库连接数据库。
任何帮助都将不胜感激。
根据Codeigniter用户指南,您可以通过$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);
我希望它对你有用!!
对于2.x版本中的PDO,在database.php中使用以下设置
$db['default']['hostname'] = 'mysql:host=localhost';
$db['default']['dbdriver'] = 'pdo';
$db['default']['database'] = 'satudent_enrollement';
希望它能帮助