New to PHP - declaring Database connection String
I am new to PHP and would like to ask, what will be the best possible way to开发者_JAVA技巧 declare application level variables and database connection strings or configurations?
How are these application level variables accessible to my scripts?
It’s commonplace (at time of writing) to store connection information in constants, in a file named config.php
or similar. Due to the sensitive nature of the file’s contents, it's also a good idea to store this file outside of the web root.
So you would have, in config.php
:
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '');
define('DBNAME', 'your_dbname');
And then to use in your scripts:
<?php
require_once('config.php');
$conn = mysql_connect(DBHOST, DBUSER, DBPASS) or die('Could not connect to database server.');
mysql_select_db(DBNAME) or die('Could not select database.');
...
Presuming your config.php
is in the same directory as your script.
Create a file named 'config.php' and include in your scripts.
//config.php
<?
define("CONN_STRING", "this is my connection string");
define("DEBUG", true);
?>
//any script.php
<?
require_once ('path/to/config.php');
if (DEBUG) {
echo "Testing...";
}
?>
Most PHP frameworks already have a config file, if you're going to use one, you just need to add your variables there.
If you're going to write your PHP code in classic plain-style (not object-oriented) you may declare your db credentials in some PHP file and then access them as global variables. example:
config.php
<?php
$db_name = 'mydb';
$db_user = 'webuser';
$dm_pass = 'pass123';
...
somefile.php
<?php
require_once ('config.php');
function db_connect() {
global $dn_name, $db_user, $db_pas
$conn = mysql_connect($dn_name, $db_user, $db_pass);
...
}
精彩评论