Reputation: 1397
I have some require
"chain" in 3 PHP files. index.php
requires db_get.php
, which is requiring db_cred.php
. All of them are in the same directory.
These are the codes:
index.php
<?php
require 'db_get.php';
$db = getDatabase();
var_dump($db);
?>
db_get.php
<?php
require 'db_cred.php';
function getDatabase()
{
$host = 'localhost';
$database = $db_name;
$username = $db_user;
$password = $db_pass;
$connectionString = 'mysql:host=' . $host . '; dbname=' . $database . '';
$attributes = array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false,
\PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8mb4'
);
return new \PDO( $connectionString, $username, $password, $attributes);
}
?>
db_cred.php (this file is auto-generated by another PHP file)
<?php $db_name="testdb"; $db_user="qNOSdZ"; $db_pass="cAHk8A"; ?>
The error I got from index.php :
Notice: Undefined variable: db_name in C:\xampp\htdocs\sipil\me\db\db_get.php on line 7
Notice: Undefined variable: db_user in C:\xampp\htdocs\sipil\me\db\db_get.php on line 8
Notice: Undefined variable: db_pass in C:\xampp\htdocs\sipil\me\db\db_get.php on line 9
Why am I getting these errors ? All those files are in the same directory.. I may be dumb, this problem has taken me for awhile, please help.
Upvotes: 0
Views: 197
Reputation: 8074
function getDatabase()
{
global $db_name;
global $db_user;
global $db_pass;
$host = 'localhost';
$database = $db_name;
$username = $db_user;
$password = $db_pass;
$connectionString = 'mysql:host=' . $host . '; dbname=' . $database . '';
$attributes = array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false,
\PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8mb4'
);
return new \PDO( $connectionString, $username, $password, $attributes);
}
Upvotes: 1
Reputation: 7446
As said in the above comments, solution should be:
<?php
require 'db_cred.php';
function getDatabase()
{
global $db_name, $db_user, $db_pass;
$host = 'localhost';
$database = $db_name;
$username = $db_user;
$password = $db_pass;
$connectionString = 'mysql:host=' . $host . '; dbname=' . $database . '';
$attributes = array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false,
\PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8mb4'
);
return new \PDO( $connectionString, $username, $password, $attributes);
}
?>
Upvotes: 1