Can't access MySQL database from cron job

Status
Not open for further replies.

belltown

Member
Messages
97
Reaction score
4
Points
8
I have a PHP script that writes to my MySQL database. The script runs fine when I run it from the web. However, when I try to run it as a cron job, it executes but gives me this error: SQLSTATE[28000] [1045] Access denied for user 'belltown_john'@'localhost' (using password: YES)

I've checked that I have int.boru.x10hosting.com listed as a remote database access host. Is there anything else I need to do to get this to work from a cron job?
 

xav0989

Community Public Relation
Community Support
Messages
4,467
Reaction score
95
Points
0
Make sure that the user has access to the database in cPanel and that it has all the required privileges. Also make sure that you correctly typed the username and password.
 

belltown

Member
Messages
97
Reaction score
4
Points
8
Make sure that the user has access to the database in cPanel and that it has all the required privileges. Also make sure that you correctly typed the username and password.

Like I said, I run the script from the web and it works fine. If I run the script -- the same script (same exact code, same username, same password) -- from a cron job, I get the access denied error. If the problem was with the username/password/priveleges, then I would get the same error when I run the script from the web wouldn't I?

Is there something different about accessing a database from a cron job versus accessing it from the web?
 

dlukin

New Member
Messages
427
Reaction score
25
Points
0
PHP:
<?php


define('DB_NAME', 'dlukin_foo');
define('DB_USER', 'dlukin_foo');
define('DB_PASSWORD', 'TheSecretWord');
define('DB_HOST', 'localhost');

$link = mysqli_connect( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );



if (!$link) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

$q = "SELECT name FROM test WHERE id=2";
$r = mysqli_query( $link, $q );

$n = mysqli_fetch_row( $r );

echo $n[0];


echo "\n<br />Success... \n<br />" . mysqli_get_host_info($link) . "\n";

mysqli_close($link);


 ?>

Works fine both as cron job and as web script for me. I am on Boru.
 

belltown

Member
Messages
97
Reaction score
4
Points
8
Re: Can't access MySQL database from cron job (Solved)

Problem solved. When a script is run from the web, the .htaccess file is executed. When it is run from a cron job, it is not. I had an environment variable set up in my .htaccess file that determined which user/password to use for my database access (x10 or my own host, etc.). That variable was not set when the cron job was run, causing it to default to the wrong db account.

Thanks, xav0989 and dlukin, for helping out.
 
Status
Not open for further replies.
Top