Renai Renai - 5 months ago 23
PHP Question

define for mysql connect

My situation:
Folder structure is /resources/website/inc/ (/resources/ is where configs are stored, /website/ holds index.php and /inc/

I have defined my constants for db connection in config.php / in resources folder.

define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'my_username' );
define ( 'DB_PASSWORD', 'my_password' );
define ( 'DB_NAME', 'my_database' );


In index.php the database is accessed and displays data.

I've come to the conclusion that it am trying to use the defined constants in config.php with a connect statement in index.php, but the constants are not passing.

This is my connect statement:

$connect = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or
die("MySQL Error: " . mysql_error());
$db = mysql_select_db(DB_NAME) or die("MySQL Error: " . mysql_error());


When i add both pieces into the config.php it works fully, but i wanted to have connect and close of connection in various areas, i do not want to have to define the variables again

Answer

You need to require (include) the config file in every other file that can be accessed through the web server.

Something alone the lines of:

config.php

define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'my_username' );
define ( 'DB_PASSWORD', 'my_password' );
define ( 'DB_NAME', 'my_database' );

public/index.php

require_once __DIR__ . '/../config.php';
// The rest of you code here

public/contact.php

require_once __DIR__ . '/../config.php';
// The rest of you code here
Comments