我有一个名为notify的表(寻找者,捐赠者,日期)列
类型(日期时间)的日期列,它存储以下格式YYYY-MM-DD HH:MM:SS
我正在尝试从通知表中选择具有最新日期的1条记录,然后进行比较与当前日期的日期,并计算两个日期之间的天数..
<?php
session_start();
$email = $_GET['email'];
date_default_timezone_set('Asia/Riyadh');
$time = date("Y-m-d H:i:s");
$note = "SELECT * FROM notify WHERE seeker='".$_SESSION['email']."'AND donor='".$email."' ORDER_BY `date` DESC LIMIT 1";
$st = $conn->prepare($note);
$st->execute();
if($found = $st->fetch(PDO::FETCH_ASSOC)){
$now = $time;
$old_date = strtotime($found['date']);
$dateif = $now - $old_date;
if(floor($dateif/(60*60*24)) >= 7){
echo "the difference between tow dates is 7 days or more";
} else { echo "difference between tow dates is less than 7 days";}
}
?>
代码不能正常工作!
我的通知表中只有一条记录,其日期为2013-04-22 09:15:47
答案 0 :(得分:4)
首先,你应该使用这样的预备语句:
$note = "SELECT *
FROM notify
WHERE seeker=:seeker AND donor=:donor
ORDER BY `date` DESC
LIMIT 1";
$st = $conn->prepare($note);
$st->execute(array(
':seeker' => $_SESSION['email'],
':donor' => $email,
);
如果没有占位符,您仍然可以使用SQL注入。
其次,您不能以这种方式将字符串与整数进行比较:
$now = $time; // string
$old_date = strtotime($found['date']); // integer
$dateif = $now - $old_date; // dunno?
您应该将苹果与苹果进行比较:
$seven_days_ago = strtotime('-7 days');
$old_date = strtotime($found['date']);
if ($old_date > $seven_days_ago) {
echo "difference between tow dates is less than 7 days";
} else {
echo "the difference between tow dates is 7 days or more";
}
答案 1 :(得分:1)
由于您的date
列不存在,因此按顺序排序是没有意义的。此外,在$_SESSION['email']
未受到保护的情况下,您将接触到SQL注入。
因此,正确的形式是使用预备语句,以及右列的顺序。 (假设是PDO,你也可以使用mysqli):
/** @var PDO $pdo - Assuming a PDO connection. */
$query = "SELECT * FROM `user` WHERE `ID` = :email ORDER BY `time` DESC";
$stmt = $pdo->prepare($query);
$stmt->execute(array($_SESSION['email']));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC); //Get all results in an associated array form.
答案 2 :(得分:1)
Jack的回答向您展示了如何正确使用预准备语句。以下是使用DATEDIFF()
简化日期计算的代码。
$note = "SELECT *, DATEDIFF(NOW(), `date`) AS date_diff
FROM notify
WHERE seeker=:seeker AND donor=:donor
ORDER_BY `date` DESC
LIMIT 1";
$st = $conn->prepare($note);
$st->execute(array(
':seeker' => $_SESSION['email'],
':donor' => $email,
);
$row = $st->fetch(PDO::FETCH_ASSOC);
// do something with $row
答案 3 :(得分:0)
如果你要将任何变量附加到字符串然后你需要使用点和oder连接它们将在where条件和$ _SESSION内部错过引号之后
$query = "SELECT * FROM user WHERE ID='".$_SESSION['email']."' ORDER_BY date, time";
答案 4 :(得分:0)
要从数据库中检索最新日期,请尝试执行以下sql查询
$query="SELECT * FROM user WHERE ID='".mysql_real_escape_string($_SESSION[email])."' ORDER_BY date,time desc limit 1";
答案 5 :(得分:0)
你忘了`这里约会。 date是mysql中的保留字,
如果你想把它作为列名放在它周围。
$note = "SELECT * FROM notify WHERE seeker='".$_SESSION['email']. "'
AND donor='".$email."' ORDER_BY `date` LIMIT 1";
答案 6 :(得分:0)
$note = "SELECT * FROM notify
WHERE
seeker=' ".$_SESSION['email']. " '
AND
donor=' ".$email." ' ORDER_BY date DESC LIMIT 1";
答案 7 :(得分:0)
为了检索最新日期,您需要按降序排序日期字段
$note = "SELECT * FROM notify WHERE seeker=' ".$_SESSION['email']. " ' AND donor=' ".$email." ' ORDER_BY date DESC LIMIT 1";