如何使用php prepared语句在mysql中选择日期范围

时间:2016-05-20 15:00:06

标签: php mysql prepared-statement

我正在使用以下准备好的声明来选择确切日期和工作正常的地方:

if($stmt = $mysqli->prepare("SELECT x FROM y WHERE mydate=?"))
{
$stmt->bind_param("s", $ReportDatetDate);
$stmt->execute();
$stmt->bind_result($xx);
while ($stmt->fetch()) 
{
echo ($xx)
}
$stmt->close();
}
else{
$mysqli->close();    
}

我需要选择Startdate和enddate之间的日期范围,但我无法编写正确的选择查询..如下所示..我怎样才能写出正确的?

if($stmt = $mysqli->prepare("SELECT x FROM y WHERE mydate between ? AND ?"))
{
$stmt->bind_param("ss", $ReportStartDate, $reportEndDate);
$stmt->execute();
$stmt->bind_result($xx);
while ($stmt->fetch()) 
{
echo ($xx)
}
$stmt->close();
}
else{
$mysqli->close();    
}

1 个答案:

答案 0 :(得分:1)

只需绑定如下参数:

$sql = "SELECT x FROM y WHERE mydate between :from_date AND :to_date";
$stmt = $db_pdo->prepare($sql);
$stmt->execute(Array(':from_date' => $from_date, ':to_date' => $to_date));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);