php - 创建 MySQL 准备语句

标签 php mysql

我在保护 SQL 数据方面的经验绝对为零。我试图通过使用准备好的语句来防止对我的 Web 服务的注入(inject)攻击。我遵循了几个教程,但我实现的每个教程都杀死了我的 PHP 脚本。我该如何保护这个查询?

$value = (integer)$_GET["name"];
$sql = "SELECT `coordinates`, `center` , `content_string` FROM Regions WHERE `id` = {$value}";

$result = $conn->query($sql);

$rows = array();

if ($result->num_rows > 0) {
        // output data of each row
        while($r = mysqli_fetch_assoc($result)) {
        $rows[] = $r;
        }
    } 

这是我的尝试:

$value = (integer)$_GET["name"];
$sql = $dbConnection->prepare('SELECT `coordinates`, `center` , `content_string` FROM Regions WHERE `id` = ?');
$sql->bind_param('i', $value);

$sql->execute();

$result = $sql->get_result();

$rows = array();

if ($result->num_rows > 0) {
        // output data of each row
        while($r = mysqli_fetch_assoc($result)) {
        $rows[] = $r;
        }
}

我不太确定为什么这段代码不起作用。

最佳答案

您必须绑定(bind)结果,下面是代码 - 它会起作用,请尝试一下。请检查我的代码中是否存在任何语法问题。否则它将起作用。

$value = (integer)$_GET["name"];
$sql = $dbConnection->prepare('SELECT 'coordinates', 'center' , 'content_string' FROM Regions WHERE `id` = ?');
$sql->bind_param('i', $value);
$sql->execute();
$sql->bind_result($coordinates, $center, $content_string)

while($sql->fetch())
{
   echo $coordinates;
   echo $center;
   echo $content_string; 
}

关于php - 创建 MySQL 准备语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45396442/

相关文章:

php - 用php替换文件中的字符串

mysql - 轮询数据库模式

java - hibernate 在选择期间锁定表多长时间?

php - 读取并解析 .cer 文件

Php mysql 在另一行中包含行ID

php - 如果 $id 是 = $id/使 css 类消失

php - jQuery post 请求中断 : Only half of post parameters arrive

mysql - 在表中插入数据时如何添加当前日期时间

mysql - 如何向我的查询添加日期条件?

php - eclipse中无BOM编码的utf8