0

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;
}
3
  • rather than your print and return statements you might want to try die() to ensure that you aren't missing an error message. Also, how are you calling your mysql class? Commented Oct 19, 2009 at 18:13
  • die(mysql_error()) should spit out the error details Commented Oct 19, 2009 at 18:21
  • Have you considered using/studying existing database access layers and/or abstractions - like e.g. docs.php.net/pdo , adodb.sourceforge.net ,doctrine-project.org , ...many, many more - before trying your own? Commented Oct 19, 2009 at 18:33

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.