class DatabaseConnection{
private $connection;
private $username;
private $password;
private $serverName;
private $database;
private $database_found = false;
//constructor with params
public function __construct($database,$username,$password,$serverName){
$this->$username = $username;
$this->$password = $password;
$this->$serverName = $serverName;
$this->$database = $database;
}
//estabilish database connection
public function connect()
{
$connection = mysql_connect($this->serverName,$this->username,$this->password);
if($connection)
{
echo "Connection was successful!\n";
$db = mysql_select_db($this->database,$connection);
if($db)
{
echo "Database found!\n";
$this->database_found = true;
}
else{
echo "Database not found!\n";
}
}
else {
echo "Failed to connect to the database!\n";
}
}
//closes connection
public function close_connection(){
mysql_close();
echo "Connection closed!\n";
}
public function getConnection(){
return $this->connection;
}
public function getDatabaseState(){
return $this->database_found;
}
}
这是我的数据库连接类。它连接到mysql,但由于某种原因,它不想连接到数据库(我试图在mysql_select_database
中插入数据库名称作为字符串,但仍然无效)。数据库存在原因它是手动创建的。谢谢你的帮助。
答案 0 :(得分:2)
您目前有:
$this->$username = $username;
这应该是:
$this->username = $username;
你有4次出现。
答案 1 :(得分:2)
mysql_*
个函数,您应该使用PDO。 Here是我找到的第一个教程。
您还可以使用$this->$username
,$this->username
。这是关于PHP类的the official tutorial。
此外,惯例是在开头使用下划线的类中编写私有变量,如下所示:
private $_username;
创建它; $this->_username
来称呼它。您还可以创建getter和setter以与变量进行交互。 (why?)
答案 2 :(得分:0)
检查您在MySQL的访问权限。 是否允许用户使用给定的DB?