I have to run a PHP file from the cron job every two hours and I am getting MySQL Database Connection Error when running the PHP script via cron. The script works correctly & exactly as I had expected it to run from the browser and even from the command line.
I have read all the answers I found on Google search results, but none of them could solve my problem. I don't think there is any answer related to my problem so I am asking this question.
Following is the database connection php script:
<?php
$cs = "localhost";
$cu = "root";
$cp = "mypassword";
// $cp = "";
$cn = "mydatabasename";
$conn = @mysqli_connect($cs, $cu, $cp, $cn);
if (!$conn) {
die("Database connection error... " . mysqli_connect_error());
}
I am running the script from browser & from command line, all is working great as I had expected, just when I run it from cronjob I get the following error:
Database connection error... Access denied for user 'root'@'localhost' (using password: NO)
Assume that root, mypassword, mydatabasename are the correct credentials as I can run the script successfully on the browser and even on command line. I am using absolute path of the PHP files in the cronjob.
I am running the cronjob by this command:
0 0-23/2 * * * php -f /var/www/html/project-name/execute-cronjob.php >> /var/www/html/project-name/output.log
I am using Ubuntu and have a VPS Server.