note 61356 deleted from function.mysql-connect by bjori
| From: | bjori@php.net | Date: | Sat, 15 Apr 2006 18:41:20 +0000 |
| Subject: | note 61356 deleted from function.mysql-connect by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-108196@lists.php.net to get a copy of this message | ||
Note Submitter: ed [at] twixcoding [dot] com
----
Personally I tend to use the following class for all my MySQL/PHP projects. As yet I've failed
to find a server where it doesn't work. Please note the class only works in PHP 5 due to the
'private' $var's inside the class.
<?php
class database {
private $ho;
private $dn;
private $du;
private $up;
/*
* $ho = Host
* $dn = Database Name
* $du = Database User
* $up = User Password
*/
public function connectionparameters($ho, $dn, $du, $up) {
// Sets the connection information
$this->ho = $ho;
$this->dn = $dn;
$this->du = $du;
$this->up = $up;
}
public function connect() {
// Establishes a mysql connection and selects the database
if(!$this->connection = mysql_connect($this->ho, $this->du, $this->up)) {
throw new exception('Connection to mysql server could not be established.');
}
if(!mysql_select_db($this->dn,$this->connection)){
throw new exception('Database could not be selected');
}
}
public function disconnect() {
// Disconnects
return mysql_close($this->connection);
}
}
?>
To establish a connection with this class:
<?php
$connection = new database;
$connection->connectionparameters('MYSQL_HOST', 'MYSQL_DB',
'MYSQL_USER', 'MYSQL_PASS');
try {
$connection->connect();
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
?>