目前我正在使用此代码,它可以工作,因为它不用说,只要我将$dateTo
更改为:dateTo
,查询就会停止工作,任何建议都会对漏洞开放大。
$from = $_POST['from'];
$dateTo = $_POST['dateTo'];
$hourTo = $_POST['hoursTo'];
$hourFrom = $_POST['hoursFrom'];
$minuteTo = $_POST['minutesTo'];
$minuteFrom = $_POST['minutesFrom'];
$sql = "SELECT sum(countAudit) AS AMZL, sum(countAudit) AS OTHER, dateEntered, count(sort_id) AS Audited, sum(error) AS error, timeEntered
FROM audits WHERE (dateEntered BETWEEN ':from' AND '$dateTo')";
$query = $db->prepare($sql);
$query->bindParam(':from', $from);
$query->bindParam(':dateTo', $dateTo);
$query->execute();
foreach($db->query($sql) as $row){
echo $row['AMZL'] . "<br>";
}
答案 0 :(得分:2)
正确使用预准备语句,不需要引用命名占位符。
另外,不要在查询语句中直接注入变量:
AND '$dateTo')";
它违背了预备陈述的目的。
不要混淆->query()
和->execute()
。只需直接使用->execute()
:
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// turn on error reporting
$from = $_POST['from'];
$dateTo = $_POST['dateTo'];
$hourTo = $_POST['hoursTo'];
$hourFrom = $_POST['hoursFrom'];
$minuteTo = $_POST['minutesTo'];
$minuteFrom = $_POST['minutesFrom'];
$sql = "
SELECT
sum(countAudit) AS AMZL,
dateEntered,
count(sort_id) AS Audited,
um(error) AS error,
timeEntered
FROM audits
WHERE (dateEntered BETWEEN :from AND :dateTo)
"; // ^remove quotes^
$query = $db->prepare($sql);
$query->bindParam(':from', $from);
$query->bindParam(':dateTo', $dateTo);
$query->execute(); // execute
$results = $query->fetchAll(PDO::FETCH_ASSOC);
// don't forget to fetch the results
foreach($results as $row){
echo $row['AMZL'] . "<br>";
}