Jump to content

Why DB connection fails with config.php but not with direct DB call ?


vincej

Recommended Posts

I have no clue why my  DB connection does not work when I try to use constants but does work with I use direct values,  ie If I do a mysql_connect=(localhost, vincej, secretpwd); is works.

 

If I do a connection with a config.php where I define the constants it fails with the error message

Unknown MySQL server host 'DB_SERVER' (11001)

 

 

Config.php :

<?php

// Database Constants
defined('DB_SERVER') ? null : define("DB_SERVER", "localhost");
defined('DB_USER')   ? null : define("DB_USER", "vincej");
defined('DB_PASS')   ? null : define("DB_PASS", "secretpwd");
defined('DB_NAME')   ? null : define("DB_NAME", "sales");

?>

 

 

Then my DB class is:

 

require_once("config.php");
<?php
class MySQLDatabase{

private $connection;

// Runs function open_connection upon creation of class. 
function __construct() {
	$this->open_connection();	
	}

// Opens connection nad selects DB 
public function open_connection() {
	$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
	if (!$this->connection) {
	die("Database connection failed: " . mysql_error());
	} else {
		$db_select = mysql_select_db(DB_NAME, $this->connection);
	if (!$db_select) {die("Database selection failed: " . mysql_error());
		}
	}
}
}
?>

 

I'm new to OOP and all help is VERY  gratefully received !

 

thansk VJ

I cut and paste both your files, moving the require_once inside the php tags, and it works fine for me.  Can you post a complete script (or scripts) which demonstrates the error message, as what you have posted does not create a class instance, so that code alone cannot generate the error.

I must be on drugs or something as it's working. I think that I got tripped up by Dreamweaver as in DW you can open more than 1 instance of the same file with their new 'Dynamic file discovery' feature and possibly I had made changes to without taking care to apply the changes correctly to the other files or indeed close them

 

I am embarrassed yet extremely grateful that you should have taken the time to help sort me out - Many thanks !!

 

VJ

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.