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

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

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

    从性能的角度来看,我知道每次执行查询时都打开与数据库的连接可能不是一个很好的做法(而且当我尝试使用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来关闭他们的东西。当然,作为程序员,我们希望自己关闭它。那很好。但是为每个查询打开和关闭数据库连接是 可怕的 想法。最好的办法是打电话 open() 从构造函数中,重命名 close() __destruct() 根据文献, __destruct 将被称为“一旦删除了对特定对象的所有引用,或者当对象被明确销毁,或者以任何顺序关闭时”。这听起来像是存放数据库连接关闭代码的理想场所。