Reputation: 169
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;
}
}
This is my class for database connection. It connects to mysql, but for some reason it doesn't want to connect to the database (I've tried to insert database name as a string in mysql_select_database
but still does not work). Database exist cause It was manually created. Thanks for the help.
Upvotes: 0
Views: 69
Reputation: 4616
mysql_*
functions are deprecated, you should rather use PDO. Here is the first tutorial I found.
You also use $this->$username
where you should use $this->username
. Here is the official tutorial about PHP classes.
Also, the convention is to write private variables in classes with an underscore at the start, like this:
private $_username;
to create it ;$this->_username
to call it.You can also create getters and setters to interact with your variables. (why?)
Upvotes: 2
Reputation: 999
You currently have:
$this->$username = $username;
this should be:
$this->username = $username;
You have 4 occurrences of this.
Upvotes: 2
Reputation: 86
Check your access rights at MySQL. Is the user allowed to use the given DB?
Upvotes: 0