Page 1 of 1
mysql_connect on each page?
Posted: Mon May 17, 2004 7:17 am
by yosuke_
Hi!
I want to create a forum. For example I have 6 pages, who needs to connect to database and update information.
Code: Select all
<?
mysql_connect("localhost","username","password");
mysql_select_db("data");
....
?>
As far as I dont change password or database name it is OK. But if I will change password or database name, I will have to edit all 6 pages and modify password or database name. What is the best way to avoid this? Is it good idea to create one page with variables $username,$password,$dbname and include this page in all 6 pages? Are there any better way? Thank you!
Posted: Mon May 17, 2004 7:24 am
by patrikG
Use a database-wrapper:
to be found either at
http://www.phpclasses.org/search.html?w ... o_search=1
or use PEAR::DB
http://pear.php.net/package/DB
or, if you want to go even bigger, use adoDB (which might be overkill):
http://php.weblogs.com/adodb
Also, you may want to read up on
passing by reference. Especially regarding DB-connections it's a must, otherwise you create unecessary overhead and, depending on traffic, could easily overload the server/database.
Posted: Mon May 17, 2004 7:32 am
by yosuke_
Thank you, but I a using mysql database, and I need some tips about my question.

Posted: Mon May 17, 2004 7:35 am
by patrikG
Database wrappers make your life much easier and, the better ones like PEAR::DB or adoDB etc, make your application database-independent.
Hence it doesn't matter if you used mySQL, postgres, Oracle, Firefox or whatever.
I would encourage you to have a look at the links

Posted: Mon May 17, 2004 7:49 am
by yosuke_
OK thank you!
Posted: Mon May 17, 2004 8:42 am
by McGruff
You'll probably find that you wind up with several site-wide constants which you want to write once so, as you say, you don't have to make multiple edits if they change.
A good way to handle this is to make a config.php file which defines a bunch of php constants.
Posted: Mon May 17, 2004 8:58 am
by lostboy
Code: Select all
<?php
$username = "someuser";
$pwd ="somepass";
$host = "localhost";
$dbname = "my_db";
//connect to db
if (!($conn=mysql_connect($host, $username, $pwd))) {
printf("error connecting to DB by user = $username and pwd=$pwd");
exit;
}
$db=mysql_select_db($dbname,$conn) or die("Unable to connect to database1");
?>
Simply include th above page (call it db.php or something like that) in each page and then reference the
$conn var to complete the connection
Code: Select all
<?
//somepage.php
include("db.php");
$sql="select ....";
$results= mysql_query($sql, $conn) or die ("Can't complete query because ".mysql_error());
//rest of page
?>