我有一些可以完美运行的MySQL代码:
<?php
include 'dbconfig.php';
$startdate = date("Y-m-d", strtotime($_GET['startdate']));
$class = ($_GET['class']);
$city = ($_GET['city']);
$coverage = ($_GET['coverage']);
$sql="SELECT day, week, month FROM pricing
WHERE '" . $startdate . "' between start_date AND end_date and class='" . $class . "' and city='" . $city . "' and coverage='" . $coverage . "'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)) {
$date_ranges = array(
'day' => $row['day'],
'week' => $row['week'],
'month' => $row['month']
);
mysqli_close($conn);
}
$json = json_encode($date_ranges);
echo $json;
?>
但是我被告知要使用PDO来提高安全性,所以我将代码转换为PDO,到此为止:]
<?php include 'dbconfig.php'; $startdate = date("Y-m-d", strtotime($_GET['startdate'])); $class = ($_GET['class']); $city = ($_GET['city']); $coverage = ($_GET['coverage']); try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("SELECT day, week, month FROM pricing WHERE :startdate between start_date AND end_date and class=:class and city=:city and coverage=:coverage"); $stmt->bindParam(':startdate', $startdate); $stmt->bindParam(':class', $class); $stmt->bindParam(':city', $city); $stmt->bindParam(':coverage', $coverage); $stmt->execute(); $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { echo $v; } } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; ?>
问题所在肯定是这个:
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC); foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { echo $v;
我正在尝试使输出看起来像这样(与第一个相同:)>
{"day":"35","week":"150","month":"650"}
有人可以告诉我如何完成此操作吗?谢谢!
我有一些可以正常运行的MySQL代码:
无论您找到什么教程,都需要放弃它。您正在编写的代码仍然容易受到SQL注入的影响,并且您并没有做太多改进。您只会使自己对本教程感到困惑。请查看https://phpdelusions.net/pdo以获得良好的PDO教程。
关于您编写的代码,您应该考虑一些更改:
如果您只是尝试以JSON格式输出查询结果,