我正在查询野生生物目击数据库,以基于查询字符串'yr'AS Dingy_Skipper_FDate显示Dingy_Skipper的第一次目击。我还想显示来自同一查询字符串'yr'的最后/最新发现AS Dingy_Skipper_LDate
我想我需要使用UNION,但是我尝试了几次,但似乎无法正常工作。我以前从未使用过UNION,因此不胜感激。大量的谢谢你!
我尝试了以下查询,但这在$ Dingy_Skipper1 = $ sp1-> query($ Dingy_Skipper);行上产生错误。
<?php
// connect
$sp1 = dbConnect('read', 'pdo');
// prepare query
$theyear = $_GET['yr'];
$Dingy_Skipper = "
SELECT rDate AS Dingy_Skipper_FDate, Dingy_Skipper
FROM wbcrecords
WHERE YEAR(rDate) = '$theyear' AND Dingy_Skipper >='1' ORDER BY rDate ASC Limit 1
UNION
SELECT rDate AS Dingy_Skipper_LDate, Dingy_Skipper
FROM wbcrecords
WHERE YEAR(rDate) = '$theyear' AND Dingy_Skipper >='1' ORDER BY rDate DESC Limit 1";
// submit query capture result
$Dingy_Skipper1 = $sp1->query($Dingy_Skipper);
// free database
$Dingy_Skipper1->closeCursor();
?>
我已经更新了查询(请参阅下文),该查询现在可以正常运行,并且我认为可以防止SQL注入吗?但是,从同一表名为Grizzled_Skipper的第二列中选择第一个和最后一个日期的最有效方法是什么,因此对于Grizzled_Skipper列以及$ Dingy_Skipper_FDate和$ Dingy_Skipper_LDate用于Dingy_Skipper列?
<?php
if (isset($_GET['yr'])) {
require_once('inc/connection.php');
$conn = dbConnect('read', 'pdo');
$sql = 'SELECT MIN(rDate) AS Dingy_Skipper_FDate, MAX(rDate) AS Dingy_Skipper_LDate, Dingy_Skipper
FROM wbcrecords
WHERE YEAR(rDate) = :yr AND Dingy_Skipper >="1"';
$searchterm = $_GET['yr'];
$Species = $conn->prepare($sql);
$Species->bindParam(':yr', $searchterm, PDO::PARAM_STR);
$Species->bindColumn(1, $Dingy_Skipper_FDate);
$Species->bindColumn(2, $Dingy_Skipper_LDate);
$Species->bindColumn(3, $Dingy_Skipper);
$Species->execute();
$numRows = $Species->rowCount();
}
?>
答案 0 :(得分:0)
您可能会使用MIN()和MAX()来获得它,如下所示:
SELECT MIN(rDate) AS Dingy_Skipper_FDate,
MAX(rDate) AS Dingy_Skipper_LDate,
Dingy_Skipper
FROM wbcrecords
WHERE YEAR(rDate) = '$theyear'
AND Dingy_Skipper >='1'
GROUP BY Dingy_Skipper
请确保对此查询中使用的变量进行转义。否则,您很容易遭受SQL注入攻击。
编辑:与其转义,不如使用准备好的语句并将$theyear
变量用作参数,会更好。