Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 452
DevGuy Avatar asked Nov 12 '22 15:11

DevGuy


1 Answers

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);
}
like image 185
Yang Avatar answered Nov 15 '22 06:11

Yang