Reputation: 1
So I'm trying to make a mysql database class, and I want to keep my db selection in a seperate method from the constructor. For some reason it the setDb() function doesn't want to work.
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;
}
Upvotes: 0
Views: 227
Reputation: 96199
You could throw an exception in case of a MySQL error, e.g.
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('...');
Maybe ErrorException() is not the best choice, but I hope you get the idea ;-)
Upvotes: 1
Reputation: 4558
You need to add curly braces after your mysql_select_db line, and before the return true line. Only the first statement under the condition is executed when the condition is met. So the function always returns false.
Upvotes: 0
Reputation: 43547
I don't see any glaring problems. Are you calling your class like below?
$db = new mysql($server, $user, $password);
$db->setDb('YOUR_DATABASE_NAME');
Upvotes: 0