user160820
user160820

Reputation: 15200

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 declare application level variables and database connection strings or configurations?

How are these application level variables accessible to my scripts?

Upvotes: 8

Views: 13075

Answers (3)

Martin Bean
Martin Bean

Reputation: 39389

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.

Upvotes: 13

heximal
heximal

Reputation: 10517

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);
  ...
}

Upvotes: 1

goenning
goenning

Reputation: 6654

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.

Upvotes: 4

Related Questions