我有一种在php 5.2中正常工作的连接,但现在没有更新到5.3版本,它会生成错误:“数据库未被选中”。这是我的剧本:
config.php:
$host = 'localhost'
$user = 'root'
$password = ''
$db = 'mydb'
Conf.class.php:
class Conf{
private $_userdb;
private $_passdb;
private $_hostdb;
private $_db;
static $_instance;
private function __construct(){
require 'config.php';
$this->_userdb=$user;
$this->_passdb=$password;
$this->_hostdb=$host;
$this->_db=$db;
}
private function __clone(){ }
public static function getInstance(){
if (!(self::$_instance instanceof self)){
self::$_instance=new self();
}
return self::$_instance;
}
public function getUserDB(){
$var=$this->_userdb;
return $var;
}
public function getHostDB(){
$var=$this->_hostdb;
return $var;
}
public function getPassDB(){
$var=$this->_passdb;
return $var;
}
public function getDB(){
$var=$this->_db;
return $var;
}
}
Db.class.php:
class Db {
private $server;
private $user;
private $password;
private $data_base;
private $link;
private $result;
static $_instance;
private function __construct() {
$this->setConnection();
$this->connect();
$this->result = null;
}
private function setConnection() {
$conf = Conf::getInstance();
$this->server = $conf->getHostDB();
$this->data_base = $conf->getDB();
$this->user = $conf->getUserDB();
$this->password = $conf->getPassDB();
}
private function __clone(){ }
public static function getInstance() {
if (!(self::$_instance instanceof self)){
self::$_instance=new self();
} return self::$_instance;
}
private function connect() {
$link=mysql_connect($this->server, $this->user, $this->password);
if ($link){
mysql_select_db($this->data_base,$link);
}
if (!$link){
die('Can not connect');
}else{
$this->link = $link;
}
}
}
显然是Db.class类,不运行函数getInstance(),因为没有从Conf.class获取数据。
我需要在Db.class和Conf.class中改变一些东西吗?
答案 0 :(得分:0)
可能是复制/粘贴问题,但您的db构造调用setConnection,而您的方法名称是setConexion。您还在配置文件中遗漏了半冒号。
否则,您的代码对我来说运行正常。可以考虑添加error_reporting(E_ALL);并从命令行进行测试。您可能有一个包含文件路径问题,而您只是没有看到错误。