PHP警告:mysqli :: __ construct():(HY000/2002):没有这样的文件或目录(Debian GNU/Linux 9) [英] PHP Warning: mysqli::__construct(): (HY000/2002): No such file or directory (Debian GNU/Linux 9)
问题描述
我在Debian 9,Apache 2.4,PHP 7.2上运行我的网站. MySQL数据库是远程的.该网站使用mysqli模块可以流畅运行.但是,当我尝试通过命令行运行PHP文件时,它失败并显示错误:
I run my website on Debian 9, Apache 2.4, PHP 7.2. MySQL database is remote. The website works smoothly using mysqli module. But when I try to run PHP file through command line it fails and displays the error:
PHP警告:mysqli :: __ construct():(HY000/2002):在...中没有这样的文件或目录 数据库连接失败:没有这样的文件或目录(2002)
PHP Warning: mysqli::__construct(): (HY000/2002): No such file or directory in ... Database connection failed: No such file or directory (2002)
我一直试图运行的PHP文件的开头是这一行:
The PHP file I've been trying to run has this line in the beginning:
require_once(__DIR__ . '/../private/initialize.php');
initialize.php
文件具有以下行:$database = db_connect();
,它将调用以下功能:
The initialize.php
file has this line: $database = db_connect();
, which calls these functions:
function db_connect() {
$connection = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
confirm_db_connect($connection);
return $connection;
}
function confirm_db_connect($connection) {
if ($connection->connect_errno) {
$msg = 'Database connection failed: ';
$msg .= $connection->connect_error;
$msg .= ' (' . $connection->connect_errno . ')';
exit($msg);
}
}
出于安全原因,数据库凭据被设置为常量,并通过以下代码从环境变量中获取:
For security reasons database credentials is set as constants and is taken from environmental variables by the following code:
define('DB_SERVER', getenv('DB_SERVER'));
define('DB_USER', getenv('DB_USER'));
define('DB_PASS', getenv('DB_PASS'));
define('DB_NAME', getenv('DB_NAME'));
通过export
命令在/etc/apache2/envvars
文件中定义的环境变量:
Environmental variables defined in /etc/apache2/envvars
file through export
command:
export DB_SERVER='*here db credential*'
export DB_USER='*here db credential*'
export DB_PASS='*here db credential*'
export DB_NAME='*here db credential*'
我检查了脚本是否正在使用环境变量,而没有.
I have checked whether the environmental variables are being taken by the script and they weren't.
echo getenv('DB_SERVER');
echo getenv('DB_USER');
echo getenv('DB_PASS');
echo getenv('DB_NAME');
似乎变量设置不正确.
有人可以解决这个问题吗?我想从命令行运行带有mysqli扩展名的PHP文件,以便使用CRON Jobs.
Can anybody help with the issue? I want to run PHP files with mysqli extension from command line so that to use CRON Jobs.
提前谢谢!
推荐答案
我解决了这个问题!
我将变量放在cron作业之前的crontab -e
文件中,但没有export
命令.
I placed my variables into crontab -e
file before cron jobs but without export
command.
DB_SERVER='*here db credential*'
DB_USER='*here db credential*'
DB_PASS='*here db credential*'
DB_NAME='*here db credential*'
它使所有cron作业都可以访问变量.
It makes the variables accessible for all cron jobs.
因此,当我使用cron作业时,它就可以正常工作!
So when I am using cron jobs it works just fine!
这篇关于PHP警告:mysqli :: __ construct():(HY000/2002):没有这样的文件或目录(Debian GNU/Linux 9)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!