New to PHP - String Database Connection Declaration

I am new to PHP and would like to ask what would be the best way to declare application level and string variables or database connection configurations?

How are these application level variables available for my scripts?

+7
php
source share
3 answers

Its usual (at the time of writing) storing connection information in constants, in a file called config.php or similar. Due to the sensitive nature of the contents of the files, it is also nice to save this file outside the root of the website.

So, you would in config.php :

 <?php define('DBHOST', 'localhost'); define('DBUSER', 'root'); define('DBPASS', ''); define('DBNAME', 'your_dbname'); 

And then 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.'); ... 

Assuming your config.php is in the same directory as your script.

+12
source share

Create a file called '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 configuration file, if you intend to use it, you just need to add your variables there.

+4
source share

If you are going to write your PHP code in a classic (non-object oriented) style, you can declare your db credentials in some PHP file and then access the 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); ... } 
+1
source share

All Articles