DevGuy
DevGuy

Reputation: 73

Can't use constants when trying to connect to database in the other file

I have a file called config.php in which i defined 4 constants:

<?php

define('HOST','localhost');
define('USER','root');
define('PASSWORD','');
define('DATABASE','some_database');

?>

What I want to do is call this script with request_once function inside the other php file called database.php which will use the constant from this file for connecting

<?php
  require_once('config.php');
  $connect = mysql_connect(HOST,USER,PASSWORD);
  $select_db = mysql_select_db(DATABASE);
?>

What i get returned is that the host,user,password and database are not defined. Why is that? This is a sample simplified code i used for connection but the essence of the problem is here. Thank you in advance.

Upvotes: 5

Views: 3803

Answers (2)

Yang
Yang

Reputation: 8701

PHP by default DO NOT SHOW Notices of undefined constants. So if you use a undefined constant PHP would simple treat that one as a string. For example,

<?php
//define('__TEST__', 'foo');

print __TEST__; //Will print __TEST__ and raise E_NOTICE if it's enabled

if you uncomment above define() PHP will print foo instead and won't raise a notice.

Personally I would suggest you to make a bit deeper test:

0) Declare error_reporting(E_ALL) in config.php
1) Check whether file exists and it readable before you include this
2) Check whether constants are actually defined before you use them

Finally, It would like this:

File: config.php

<?php

error_reporting(E_ALL);

define('HOST','localhost');
define('USER','root');
define('PASSWORD','');
define('DATABASE','some_database');

File: dbconnection.php

<?php

//require() will produce FATAL error if inclusion fails, so we're OK
require_once('config.php'); 


if ( defined('HOST') && defined('USER') && defined('PASSWORD') && defined('DATABASE') ){

 $connect = mysql_connect(HOST,USER,PASSWORD);
 $select_db = mysql_select_db(DATABASE);

} else {

  trigger_error('Some constants are missing', E_USER_ERROR);
}

Upvotes: 1

ROY Finley
ROY Finley

Reputation: 1416

you can try Include() just to see if it makes a difference. also if you are working on a local machine, you may want to use :

require_once(dirname(__FILE__) . "/config.php");

You should look into MYSQLI or PDO as the mysql functions are depreciated now:

 define("DB_HOST", "");
 define("DB_USERNAME", "");
 define("DB_PASSWORD", "");
 define("DB_NAME", "");

    $Mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
        if ($Mysqli->connect_errno)
        {
            echo "Failed to connect to MySQL: (" . $Mysqli->connect_errno . ") " . $Mysqli->connect_error;
            $Mysqli->close();
        }

Upvotes: 0

Related Questions