【问题标题】:Creating MySQL Prepared Statement创建 MySQL 准备好的语句
【发布时间】:2017-07-30 04:41:42
【问题描述】:

我在保护我的 SQL 数据方面的经验绝对为零。我试图通过使用准备好的语句来防止对我的 Web 服务的注入攻击。我已经学习了几个教程,但是我实现的每个教程都杀死了我的 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;
        }
}

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

【问题讨论】:

  • 请展示您迄今为止在实现准备好的语句方面的最佳尝试,以便我们可以帮助您找出为什么它会杀死您的 PHP 脚本
  • 查看此页面以获得一些建议:php.net/manual/en/mysqli.prepare.php。如果您有任何问题,请发布更新您的问题的错误。
  • 为什么要混合 mysqli 调用的过程和面向对象风格?
  • 代码到底是什么“不起作用”?你看到了什么错误(如果有的话)?
  • @BeetleJuice 我刚刚收到一个标准的 HTTP 500 错误,我知道它没有用

标签: php mysql


【解决方案1】:

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

$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; 
}

【讨论】:

  • 很遗憾,此代码不起作用。早上我会看错误日志。
【解决方案2】:

用 MySQLi 准备的语句

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);

// set parameters and execute
$username= "John";
$email = "john@example.com";
$stmt->execute();

$username= "Mary";
$email = "mary@example.com";
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();

PHP 提示和技巧。 http://www.phptherightway.com/

如果您担心安全问题,这是我非常喜欢的话题。 What are the best PHP input sanitizing functions?.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 2011-09-16
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多