好的,所以我有许多分散的拼图。我正在尝试制作一个应用程序,每月更新我网站底部的报价(即“月度报价”)。我使用PHP访问MySQL服务器,MySQL服务器中有引号。
在数据库中,该表称为“引号”,其列有“quote_id”,“quotation”,“author”和“datetime_used”。 'datetime_used'列的默认值为1991,我用它来检查我是否在去年使用过该报价。如果随机选择的报价时间小于当前时间减去1年,那么该报价将用作该月的新报价。如果使用引号,则'datetime_used'将更新为当前时间。
我认为要经历的步骤是: 1.运行一个运行以下PHP脚本的cron作业(每月运行一次):
<?php
//Make connection
$connect = mysqli_connect("localhost","user","password","dbname");
//Check connection
if (mysqli_connect_errno($connect))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Run query
//Select random quote
$result = mysqli_query($connect,
"SELECT quotation, author FROM quotes
WHERE datetime_used <= NOW() - INTERVAL 1 YEAR
ORDER BY RAND()
LIMIT 1");
$row = $mysqli_fetch_array($result);
$quote = $row['quotation'];
//Update the datetime_used column to NOW()
mysqli_query($connect,"
UPDATE quotes SET datetime_used=NOW()
WHERE quotation='$quote'");
mysqli_close($connect);
?>
2。然后将上面的cron作业脚本生成的$ quote包含在我的网站代码中:
<footer>
<p>Quote of the month:
<?php
//INCLUDE THE $quote SOMEHOW
echo $quote;
?>
</p>
</footer>
所以我的问题是如何让cron作业以某种方式更新$ quote变量,以便我可以将更新的变量包含在我的网站代码中。或者有更好的方法吗?
编辑:我提出的代码似乎有效。
<?php
//Make connection
$connect = mysqli_connect("localhost","root","root","test");
//Check connection
if (mysqli_connect_errno($connect)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Check for month difference between this month and most recently used quote as well as get the quote and author to store
$check = mysqli_query($connect, 'SELECT MONTH(NOW())-MONTH(datetime_used) AS m, quotation, author FROM quotes ORDER BY datetime_used DESC LIMIT 1');
$checkarray = mysqli_fetch_array($check);
$quote = $checkarray['quotation'];
$author = $checkarray['author'];
//If the month difference if 1 or greater, it selects a new quote
if ($checkarray['m']) {
$result = mysqli_query($connect,
"SELECT quotation, author FROM quotes
WHERE datetime_used <= NOW() - INTERVAL 1 YEAR
ORDER BY RAND()
LIMIT 1");
$row = mysqli_fetch_array($result);
$quote = $row['quotation'];
$author = $row['author'];
//Update the datetime_used column to NOW()
mysqli_query($connect,
"UPDATE quotes SET datetime_used=NOW()
WHERE quotation='$quote' AND author='$author'");
}
mysqli_close($connect);
echo "\"$quote\"
</cite>
-$author";
?>
答案 0 :(得分:0)
我认为你的步骤过于复杂。你应该只需要:
不需要Cron工作。我假设这是一个低流量站点,因此对每个页面访问运行检查不是性能问题。如果确实需要,可以使用缓存系统缓存选定的引用,避免在30天后检查数据库。