开发者

Mysql db class - trouble connecting

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->da开发者_如何学运维tabase = $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;
}


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 ;-)


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');


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜