2017-04-24 51 views
1

我试图用我的1and1托管来设置一个cron作业。如果我写一个简单的PHP代码,cron运行正常。但是当包含数据库连接并运行代码时,它不会运行。1and1 Cron未运行mysql查询

的代码是打击:

<?php mail('[email protected]','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 protected]','Latest Blog',$latest_blog); 
?> 

正如你可以看到,在页面的顶部,我插一个简单的电子邮件功能,如果cron的作品只是为了测试。我每分钟都收到一封电子邮件。但是在这个简单的代码下面,我写了数据库查询并尝试用数据库中的信息发送电子邮件,但它不起作用。

有没有人有任何想法为什么?

+0

使用'try-catch'模块来获得一个例外的电子邮件.... http://php.net/manual/en/language.exceptions.php – Hackerman

+0

'static $ connection;'this this甚至有效? – Augwa

回答

0

(我假设程序没有工作在常规环境下运行?)

一个cron作业在不同的环境比web应用的工作运行。 一些可能的原因:

  1. 也许DATEBASE东西是工作,但在电子邮件声明中是行不通的。开头的邮件(..)声明与最后的电子邮件(..)声明不同。尝试在最后使用相同的邮件(..)语句。

  2. 尝试邮寄__ROOT__常数。这是你的预期吗?

  3. 工作目录是不同的。我总是用下面一行在我的CLI和cron作业的开始(您可能需要根据您的具体情况..部分删除。): chdir(realpath(__DIR__ . '/..'));

  4. 我的服务器上的CLI/cron作业的情况下实例下列环境变量为空:DOCUMENT_ROOT,HTTP_HOST,SERVER_SOFTWARE(也可能是其他人)

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

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

我希望这有助于。

+0

谢谢你的回答。邮件功能不同,因为我想看看一个PHP邮件功能,并包括PHP邮件功能的作品。 email()函数用于phpmailer并且它可以工作。我也会尝试你的其他建议 – Vurkac