使用准备好的语句和 fetchAll() 显示到 table
using prepared statements and fetchAll() to display to a table
我正在尝试让我的代码 SQL 注入安全,我在将 pdo 数据转换为数组然后比较行数据时遇到问题。
我一直在阅读 how to prevent sql injection as well as fetchAll() documentation 和
how to handle SELECT statements with pdo.
这是相关代码。我相信它准备了语句,然后执行它,然后 table 被获取并存储在 $data 中,它被传递给 $row,然后它查找播放器列并将其与登录用户进行比较将基于上下文的代码获取到 运行。问题出在哪里?
$stmt = $pdo->prepare("SELECT * FROM userdata");
$stmt->execute();
$data = $stmt->fetchAll();
echo "<table border='1'>
<tr>
<th>username</th>
<th>words</th>
</tr>";
while($row = $data)
{
echo $row['player'];
echo "<tr>";
echo "<td>" . $row['player'] . "</td>";
if($row['player'] == $logedInUsername)
{
echo "<td>" . $row['words'] . "<a href='edityourword.php?edit=$row[words]'> edit</a></td>";
}
else
{
echo "<td>" . $row['words'] . "</td>";
}
echo "</tr>";
}
echo "</table>";
我现在的错误重复出现,这里是while循环不断打印的段。
Notice: Undefined index: player on line 41
Notice: Undefined index: player on line 43
Notice: Undefined index: player on line 44
Notice: Undefined index: words on line 50
Notice: Undefined index: player on line 41
Notice: Undefined index: player on line 43
Notice: Undefined index: player on line 44
Notice: Undefined index: words on line 50
你有两个选择。按照@NigelRen 的建议将 while 循环更改为 foreach 循环,或者使用 fetch
方法从数据库中一条一条地获取每条记录。
foreach ( $data as $row) {
// ...
}
// or
// Remove $data = $stmt->fetchAll();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// ...
}
我正在尝试让我的代码 SQL 注入安全,我在将 pdo 数据转换为数组然后比较行数据时遇到问题。
我一直在阅读 how to prevent sql injection as well as fetchAll() documentation 和 how to handle SELECT statements with pdo.
这是相关代码。我相信它准备了语句,然后执行它,然后 table 被获取并存储在 $data 中,它被传递给 $row,然后它查找播放器列并将其与登录用户进行比较将基于上下文的代码获取到 运行。问题出在哪里?
$stmt = $pdo->prepare("SELECT * FROM userdata");
$stmt->execute();
$data = $stmt->fetchAll();
echo "<table border='1'>
<tr>
<th>username</th>
<th>words</th>
</tr>";
while($row = $data)
{
echo $row['player'];
echo "<tr>";
echo "<td>" . $row['player'] . "</td>";
if($row['player'] == $logedInUsername)
{
echo "<td>" . $row['words'] . "<a href='edityourword.php?edit=$row[words]'> edit</a></td>";
}
else
{
echo "<td>" . $row['words'] . "</td>";
}
echo "</tr>";
}
echo "</table>";
我现在的错误重复出现,这里是while循环不断打印的段。
Notice: Undefined index: player on line 41
Notice: Undefined index: player on line 43
Notice: Undefined index: player on line 44
Notice: Undefined index: words on line 50
Notice: Undefined index: player on line 41
Notice: Undefined index: player on line 43
Notice: Undefined index: player on line 44
Notice: Undefined index: words on line 50
你有两个选择。按照@NigelRen 的建议将 while 循环更改为 foreach 循环,或者使用 fetch
方法从数据库中一条一条地获取每条记录。
foreach ( $data as $row) {
// ...
}
// or
// Remove $data = $stmt->fetchAll();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// ...
}