【问题标题】:Mysql db class - trouble connectingMysql db类 - 连接问题
【发布时间】:2009-10-19 18:00:14
【问题描述】:

所以我正在尝试创建一个 mysql 数据库类,并且我想将我的数据库选择保留在与构造函数不同的方法中。由于某种原因,setDb() 函数不想工作。

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

【问题讨论】:

  • 而不是您的 print 和 return 语句,您可能想尝试 die() 以确保您不会丢失错误消息。另外,你是怎么称呼你的 mysql 类的?
  • die(mysql_error()) 应该吐出错误细节
  • 您是否考虑过使用/研究现有的数据库访问层和/或抽象——例如docs.php.net/pdo , adodb.sourceforge.net ,doctrine-project.org , ...很多很多 - 在尝试自己之前?

标签: php mysql database-connection


【解决方案1】:

如果发生 MySQL 错误,您可以抛出异常,例如

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

也许ErrorException() 不是最好的选择,但我希望你能明白 ;-)

【讨论】:

    【解决方案2】:

    我没有看到任何明显的问题。你是在像下面这样打电话给你的班级吗?

    $db = new mysql($server, $user, $password);
    $db->setDb('YOUR_DATABASE_NAME');
    

    【讨论】:

      【解决方案3】:

      您需要在 mysql_select_db 行之后和 return true 行之前添加花括号。当条件满足时,只执行条件下的第一条语句。所以函数总是返回false。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-23
        • 2020-05-25
        • 1970-01-01
        • 2010-09-23
        • 2011-02-16
        • 1970-01-01
        相关资源
        最近更新 更多