tags:

views:

35

answers:

4

Hello,

I am new to PHP and would like to ask, what will be the best possible way to declare application level variables and Database connection Strings or configrations.

How these application level variables are accessible to my Scripts.

A: 

check w3schools tutorials http://w3schools.com/php/php_mysql_connect.asp

mwafi
+2  A: 

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.

Guilherme Oenning
A: 

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);
  ...
}
heximal
+1  A: 

It's commonplace 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.

Martin Bean