我正在尝试从 mySQL 数据库中选择数据,
我执行以下代码:
<?php $_SESSION["dog_park"] = $_GET['keyword'] ?>
<div class="review"> <!-- Creating a div with the class 'review -->
<!-- but POST varibale in here for dog park name -->
<h1><?php echo $_SESSION["dog_park"]; ?></h1>
<table border="1" cellspacing="5" cellpadding="5" width="100%">
<thead>
<tr>
<th>Park Name</th>
<th>Street</th>
<th>Suburb</th>
<th>Dog Park Area (m2)</th>
</tr>
</thead>
<tbody>
<?php
$result = $conn->prepare("SELECT * FROM dog_parks.items where suburb = '$_SESSION[dog_park]'");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<tr>
<td><label><?php echo $row['Park_Name']; ?></label></td>
<td><label><?php echo $row['Street']; ?></label></td>
<td><label><?php echo $row['Suburb']; ?></label></td>
<td><label><?php echo $row['Dog_Park_Area_(m2)']; ?></label></td>
</tr>
<?php } ?>
</tbody>
</table>
这与 session 变量有关,如果我为 mySQL 查询输入静态值,它将正确显示表数据,但当 $_SESSION 变量存在时会失败。
最佳答案
该字符串包含引号,这会破坏 SQL 字符串封装。使用准备好的语句,因为它们应该是参数化的,问题就会消失。
$result = $conn->prepare("SELECT * FROM dog_parks.items where suburb = ?");
$result->execute(array($_SESSION[dog_park]));
您可以阅读更多内容:
http://php.net/manual/en/pdo.prepared-statements.php
How can I prevent SQL injection in PHP?
您的查询运行情况如下:
SELECT * FROM dog_parks.items where suburb = ''Tramway''
(粗略地说,如果您包含错误消息的文本,而不是图像,我可以提供真正的查询)
这是无效的,因为 ''
是您要比较的内容。 Tramway''
它不知道该怎么办。巧合的是,这就是 SQL 注入(inject)的发生方式。
关于PHP $_SESSION 变量导致 mySQL 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37190345/