Mysql in cron job

Is there some trick to getting mysql working in a cron job?
I’ve got a PHP function that works fine when called by the web server, but it fails when cron calls it.

The function first tests for the mysqli_connect function:

$si = function_exists(‘mysqli_connect’);
if (!$si)
echo “Whoops! MySQLi does not appear to be compiled or enabled properly!”;

This fails.

Here’s what cron mails to me (personal info removed):

Whoops! MySQLi does not appear to be compiled or enabled properly!

Fatal error: Call to undefined function: mysqli_commit() in /home/XXXX/XXXX/includes/DBUtils.php on line 689

The call to mysqli_commit obviously comes later in the file.

I read somewhere that cron doesn’t have environment variables available to it. Could that be the problem?

How can I fix this?


I tried removing the line from the top of the php file:
#! /usr/local/bin/php -q

the next email I got from cron started with this:

X-Powered-By: PHP/4.4.7

The version of PHP used by the website is “PHP Version 5.2.3” as reported by phpinfo.

Hmmm… I just tried using the web panel interface to make a cron job, and that works.

Would still be nice to know what I was doing wrong from the command-line though.

You shouldn’t remove the #! /usr/local/bin/php -q line, as it is required for the cron to run properly AFAIR.

instead of assigning the boolean result from function_exists to a variable and then checking that, you may try checking it directly:

<?php if (!function_exists('function')) { echo "it doesn't exist
\n"; } ?>

if you do it your way, you may wind up checking if variable $si has been set with a value, which even if such value is FALSE, would eval as TRUE (since $si is set with a value, which is in this case FALSE)

take this with a grain of salt anyway, this is rather new to me

I have crons running on my domain which make extensive use of mysql and they run with no problem at all so I tend to think your problem is in the scripting and not related to the fact you’re using the cron to access the database

good luck!