【发布时间】: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 是否工作。我每分钟都会收到一封电子邮件。但是在这个简单的代码下面,我编写了数据库查询并尝试使用数据库中的信息发送电子邮件,但它不起作用。
有人知道为什么吗?
【问题讨论】:
-
使用
try-catch块以获取电子邮件,但例外情况...php.net/manual/en/language.exceptions.php -
static $connection;这还有效吗?