note 38075 added to function.mysql-connect
| From: | calegoatcalegodotcc at rn2 dot php dot net | Date: | Sun, 07 Dec 2003 17:04:45 +0000 |
| Subject: | note 38075 added to function.mysql-connect | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-61596@lists.php.net to get a copy of this message | ||
mysql_connect() can be called through the constructor for your database class, if you have one. This
is a handy little function and saves you having to place $DB->connect() on every one of your
pages.
<?php
class DB {
function DB() {
$this->host = "mysql.host.com";
$this->db = "myDatabase";
$this->user = "root";
$this->pass = "mysql";
$this->link = mysql_connect($this->host, $this->user, $this->pass);
mysql_select_db($this->db);
}
}
?>
And then, on each of your pages, include the file with your database class, and then...
<?php
$DB = new DB;
?>
And you are connected and selected to your database. $DB->link now acts as the resource
identifier, although you could also apply it to a simple variable like $link, since this becomes a
superglobal.
Even though it's unnecessary, you could also do something like this:
<?php
class DB {
function DB() {
$this->host = "mysql.host.com";
$this->db = "myDatabase";
$this->user = "root";
$this->pass = "mysql";
$this->link = mysql_connect($this->host, $this->user, $this->pass);
mysql_select_db($this->db);
register_shutdown_function($this->close);
}
function close() {
mysql_close($this->link);
}
}
?>
That code is also useful in that it makes each class have its own specific link. So to open multiple
database connections, you simply create multiple database classes.
<?php
$DB_admin = new DB;
$DB_user = new DB;
?>
And then you have two separate database connections that will close automatically and have their own
resource identifier. If you don't want to remember to place the resource identifier in each
query, no worries. Simply use the DB class' query() function with the proper instance of the DB
class.
<?php
class DB {
function DB() {
$this->host = "mysql.host.com";
$this->db = "myDatabase";
$this->user = "root";
$this->pass = "mysql";
$this->link = mysql_connect($this->host, $this->user, $this->pass);
mysql_select_db($this->db);
register_shutdown_function($this->close);
}
function query($query) {
$result = mysql_query($query, $this->link);
return $result;
}
function close() {
mysql_close($this->link);
}
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.mysql-connect.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+38075
Delete -- http://master.php.net/manage/user-notes.php?action=delete+38075&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+38075&report=yes
Search -- http://master.php.net/manage/user-notes.php