所以我正在尝试创建一个mysql数据库类,并且我希望将db选择保留在构造函数的单独方法中。由于某种原因,setDb()函数不想工作。
class mysql
{
public function __construct($server,$user,$pass)
{
if(!$this->mysql_connection = mysql_connect($server,$user,$pass))
print 'Could not connect to MySQL';
}
public function setDb($dbname)
{
$this->database = $dbname;
if(!mysql_select_db($this->database,$this->mysql_connection))
$this->database = '';
print 'Could not connect to the MySQL database';
return false;
return true;
}
private $database;
private $mysql_connection;
}
答案 0 :(得分:1)
如果出现MySQL错误,您可以抛出异常,例如
class DbMySQL
{
protected $database;
protected $mysql_connection;
public function __construct($server,$user,$pass)
{
$this->mysql_connection = mysql_connect($server,$user,$pass);
if( !$this->mysql_connection ) {
throw new ErrorException(mysql_error(), mysql_errno());
}
}
public function setDb($dbname)
{
if ( !mysql_select_db($dbname, $this->mysql_connection) ) {
throw new ErrorException(mysql_error($this->mysql_connection), mysql_errno($this->mysql_connection));
}
else {
$this->database = $dbname;
}
return $this;
}
}
$m = new DbMySQL('localhost', '...', '...');
$m->setDB('...');
也许ErrorException()不是最佳选择,但我希望你明白这一点; - )
答案 1 :(得分:0)
我没有看到任何明显的问题。你是在打电话给你的班级吗?
$db = new mysql($server, $user, $password);
$db->setDb('YOUR_DATABASE_NAME');
答案 2 :(得分:0)
您需要在mysql_select_db行之后和返回true行之前添加花括号。只有满足条件时才会执行条件下的第一个语句。所以函数总是返回false。