PDO-使用准备好的语句将所有sql数据放入html表中 [英] PDO - Putting all sql data into an html table using prepared statement

查看:47
本文介绍了PDO-使用准备好的语句将所有sql数据放入html表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的表中获取所有数据并将其显示在html表中,但是我不确定如何使用准备好的语句来保护我免于sql注入.

I want to fetch all the data from my table and display it in an html table but I'm not sure how to do with a prepared statement that will protect me from sql injection.

我已经阅读到它应该类似于:

I've read that it should look something like:

$getPlayers = $db->prepare("SELECT * FROM Player WHERE name = :name");

但是我不确定如何使用'WHERE'方法从数据库中获取所有数据.

But I'm not sure how to use the method using 'WHERE' to get all my data from the database.

到目前为止,这是我的代码.它可以正常工作并获取我所有的数据,但是我认为它不受sql注入的影响,对吗?

This is my code so far. It works and gets me all my data but I dont think its secure from sql injection, is it?

$getPlayers = $db->prepare("SELECT * FROM Player");
$getPlayers->execute();

$players = $getPlayers->fetchAll();

echo "<table>";
echo "<tr><th>Name</th><th>Games Played</th><th>Tries</th></tr>";


foreach( $players as $row) {
    echo "<tr>";
    echo "<td>".$row['name']."</td>";
    echo "<td>".$row['games_played']."</td>";
    echo "<td>".$row['tries']."</td>";
    echo "</tr>";
}

echo "</table>";

推荐答案

SQL注入只是需要将用户输入的数据发送到数据库的问题. 像SELECT * FROM Player这样的查询不包含用户数据.因此,从SQL注入完全安全.

SQL Injection is only a problem where user-entered data needs to be sent to your database. A query like SELECT * FROM Player includes no user data. It's entirely safe from SQL Injection for that reason.

实际上,在这种情况下,使用准备好的语句没有任何好处.一条准备好的语句将在需要时对数据库进行两次调用.

In fact, in this case, there's no benefit in using a prepared statement. A prepared statement here will make two calls to the database when one will do.

您可以执行以下操作:

$getPlayers = $db->query("SELECT * FROM Player");
foreach ($getPlayers as $player) {
  // do something
}

没有准备,没有绑定,只有一个对数据库的调用.

No preparation, no binding, and just one call to the database.

这篇关于PDO-使用准备好的语句将所有sql数据放入html表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆