代码之家  ›  专栏  ›  技术社区  ›  rogeriopvl

这个PHP类是否针对MySQL数据库访问进行了优化?

  •  2
  • rogeriopvl  · 技术社区  · 16 年前

    我已经编写了一个快速的PHP类来简化对MySQL数据库的访问。这个类工作正常,并且有一个query()方法,它打开连接,执行查询,然后关闭连接(我知道脚本完成后,连接应该由php本身关闭,但我不太喜欢依赖它)。

    从性能的角度来看,我知道每次执行查询时总是打开与数据库的连接可能不是一个很好的实践(而且,当我尝试使用mysql_real_escape_string()过滤输入时,它不起作用,因为没有活动的数据库连接)。但我想更清楚地说明这一点。做错事了吗?为什么?我还想知道好的替代方法。

    这是课程:

    class DB {
    
    private $conn;
    
    //database data
    private $dbhost;
    private $dbname;
    private $dbuser;
    private $dbpass;
    
    /**
     * Constructor
     * @dbhost string the database host
     * @dbname string the database name
     * @dbuser string the database username
     * @dbpass string the database password
     */
    public function __construct ($dbhost, $dbname, $dbuser, $dbpass)
    {
        $this->dbhost = $dbhost;
        $this->dbname = $dbname;
        $this->dbuser = $dbuser;
        $this->dbpass = $dbpass;
    }
    
    /**
     * Connects to mysql database
     */
    private function open ()
    {
        $this->conn = mysql_connect ($this->dbhost, $this->dbuser, $this->dbpass)
        or die ("Error connecting to database");
    
        mysql_select_db ($this->dbname) or die ("Error selecting database");
    }
    
    /**
     * Closes the connection to a database
     */
    private function close ()
    {
        mysql_close($this->conn);
    }
    
    /**
     * Executes a given query string
     * @param string $query the query to execute
     * @return mixed the result object on success, False otherwise
     */
    public function query ($query)
    {   
        $this->open();
        $result = mysql_query($query, $this->conn)
        or die ("Error executing query ".$query." ".mysql_error());
    
        $this->close();
        return $result;
    
    }
    

    }

    1 回复  |  直到 16 年前
        1
  •  13
  •   Paolo Bergantino    16 年前

    (我知道在脚本完成后,连接应该由PHP本身关闭,但我不太喜欢依赖它)。

    为什么?这是语言的一个特点。没有理由不相信它。很多网站都是靠php来关闭他们的东西。当然,作为程序员,我们希望自己关闭它。那很好。但是,为每个查询打开和关闭数据库连接是 好可怕 想法。最好的办法是打电话 open() 从构造函数中,并重命名 close() __destruct() . 根据文件, __destruct 将被称为“一旦所有对某个特定对象的引用被删除,或者对象被显式销毁,或者以关闭顺序的任何顺序。”听起来是存放数据库连接关闭代码的理想场所。