Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New to PHP - declaring Database connection String

Tags:

php

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?

like image 328
user160820 Avatar asked Oct 26 '10 10:10

user160820


2 Answers

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.

like image 148
Martin Bean Avatar answered Sep 24 '22 04:09

Martin Bean


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.

like image 29
goenning Avatar answered Sep 23 '22 04:09

goenning