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