我在3个PHP文件中有一些require
“链”。 index.php
需要db_get.php
,这需要db_cred.php
。所有这些都在相同的目录中。
这些是代码:
的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 (此文件由另一个PHP文件自动生成)
<?php $db_name="testdb"; $db_user="qNOSdZ"; $db_pass="cAHk8A"; ?>
我从 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
为什么我会收到这些错误?所有这些文件都在同一个目录中.. 我可能是愚蠢的,这个问题花了我一段时间,请帮助。
答案 0 :(得分:1)
如上述评论所述,解决方案应该是:
<?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);
}
?>
答案 1 :(得分:1)
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);
}