【问题标题】:1and1 Cron not running the mysql query1and1 Cron 未运行 mysql 查询
【发布时间】:2017-04-25 16:02:12
【问题描述】:

我正在尝试使用我的 1and1 托管设置 cron 作业。如果我编写一个简单的 php 代码,cron 运行正常。但是当包含数据库连接并运行代码时,它并没有运行。

代码很牛逼:

    <?php mail('email@gmail.com','At4U test cron','testing cron'); ?>

<?php
    define('__ROOT__', dirname(dirname(__FILE__)));
    require_once(__ROOT__.'/AT4U/extensions/phpmailer/class.phpmailer.php');
    include(__ROOT__.'/AT4U/core/functions/general.php');
    function db_connect() {

        $db_name    = '***************';
        $db_user    = '***************';
        $host       = '***************';
        $password   = '***************';

        // Define connection as a static variable, to avoid connecting more than once 
        static $connection;

        // Try and connect to the database, if a connection has not been established yet
        if(!isset($connection)) {

            $connection = mysqli_connect($host,$db_user,$password,$db_name);
        }

        // If connection was not successful, handle the error
        if($connection === false) {
            // Handle error - notify administrator, log to a file, show an error screen, etc.
            return mysqli_connect_error(); 
        }
        return $connection;
    }

    $con = db_connect();

    $sql = "SELECT * FROM blog WHERE active = 1 ORDER BY id DESC LIMIT 1";
    $result = $con->query($sql);

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $latest_blog = $row['title'];
        }
    }

    email('email@gmail.com','Latest Blog',$latest_blog); 
?>

如您所见,在页面顶部,我插入了一个简单的电子邮件功能,只是为了测试 cron 是否工作。我每分钟都会收到一封电子邮件。但是在这个简单的代码下面,我编写了数据库查询并尝试使用数据库中的信息发送电子邮件,但它不起作用。

有人知道为什么吗?

【问题讨论】:

标签: php mysql cron


【解决方案1】:

(我假设程序确实可以在常规环境中运行?)

cron 作业与 Web 作业在不同的环境中运行。 一些可能的原因:

  1. 也许数据库的东西正在工作,但电子邮件声明不起作用。开头的 mail(..) 语句与结尾的 email(..) 语句不同。尝试在末尾使用相同的 mail(..) 语句。

  2. 尝试发送__ROOT__constant。那是你所期望的吗?

  3. 工作目录不同。我总是在 CLI 和 cron 作业的开头使用以下行(根据您的情况,您可能希望删除 .. 部分。): chdir(realpath(__DIR__ . '/..'));

  4. 在我的服务器上,例如 CLI/cron 作业,以下环境变量为空:DOCUMENT_ROOT、HTTP_HOST、SERVER_SOFTWARE(可能还有其他)

  5. 您包含的文件是否与在 CLI/cron 环境中运行兼容?

  6. 它甚至可能使用其他 php.ini。

我希望这会有所帮助。

【讨论】:

  • 感谢您的回答。邮件功能不同,因为我想看看一个 php 邮件功能和包含的 php 邮件程序功能是否有效。 email() 函数用于 phpmailer 并且可以正常工作。我也会尝试你的其他建议
猜你喜欢
  • 2014-02-07
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2016-05-09
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
相关资源
最近更新 更多