Reputation: 54104
I've wrote a quick PHP class to ease the access to a mysql database. The class works ok, and has a query() method that opens up the connection, executes the query and then closes the connection (I know that the connection is supposed to close by PHP itself after the script finishes, but I don't like to rely very much on that).
From a performance standpoint, I know that always opening a connection to a database every time I execute a query may not be a very good practice (and also that when I try to use mysql_real_escape_string() to filter input, it doesn't work, because there's no active database connection). But I would like to be more clarified about this. Is it very wrong to do? Why? And I would also like to know about good alternatives to this.
Here's the class:
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;
}
}
Upvotes: 2
Views: 843
Reputation: 488554
(I know that the connection is supposed to close by PHP itself after the script finishes, but I don't like to rely very much on that).
Why? This is a feature of the language. There's no reason to not trust it. A lot of websites are running just fine counting on PHP to close their stuff. As programmers, of course, we want to close it ourselves. That's fine. But opening and closing a database connection for every query is a horrible idea. The better way to do it is to call open()
from your constructor, and rename your close()
to __destruct()
. According to the documentation, __destruct
will be called "as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence." Sounds like an ideal place to stash away the closing code for your database connection.
Upvotes: 13