SQL注入检查和php抛出错误

时间:2012-12-09 16:24:22

标签: php sql

我有两个问题

  1. 以下代码是一种对SQL注入实践的好方法(它似乎可以作为插入方法工作)

  2. 如何在完整示例中放置此错误消息:

    if (!mysqli_query($query,$link))
    {
        die('Error: ' . mysqli_error());
    }
    
  3. 这是完整的例子:

    <?php
    
    $link = mysqli_connect("localhost","root","", "runtracker");
    if (!$link)
    {
        die('Could not connect: ' . mysqli_error());
    }
    
    $query="INSERT INTO userinfo (UserName) VALUES (?)";
    
    if ($stmt = mysqli_prepare($link, $query)) {
    
        // Lets create the variables
        $name = $_POST['UserName'];
    
        // Bind the variables and execute the query
        mysqli_stmt_bind_param($stmt,"s", $name);
        mysqli_stmt_execute($stmt);
    
        // And now we close the statement
        mysqli_stmt_close($stmt);
    }
    
    echo "1 record added";
    
    mysqli_close($link);
    ?>
    

1 个答案:

答案 0 :(得分:1)

是的,对于SQL查询中的动态值,使用绑定参数是防止SQL注入的好方法。有关SQL注入的更多信息,您可能会喜欢我的演示文稿SQL Injection Myths and Fallacies

在调用API函数后检查错误是正确的。大多数mysqli函数在出错时返回FALSE,但连接的处理方式略有不同。

我也希望将Mysqli错误输出到我可以阅读的日志中,但不能输出到用户的浏览器。

以下是我编码的方法:

<?php

$mysqli = new mysqli("localhost","root","", "runtracker");
if (mysqli_connect_error())
{
    error_log("Connect error in file ".__FILE__.", line ".__LINE__.": "
      .mysqli_connect_error());
    die("Could not connect to database");
}

if (($stmt = $mysqli->prepare($link, $query)) === false) {
  error_log("Error on prepare in file ".__FILE__.", line ".__LINE__.": "
    .$mysqli->error);
  die('Error on prepare');
}

// Lets create the variables
$name = $_POST['UserName'];

// Bind the variables and execute the query
if ($stmt->bind_param("s", $name) === false) {
  error_log("Error on bind in file ".__FILE__.", line ".__LINE__.": "
    .$stmt->error);
  die('Error on bind');
}
if ($stmt->execute() === false) {
  error_log("Error on execute in file ".__FILE__.", line ".__LINE__.": "
    .$stmt->error);
  die('Error on execute');
}

// And now we close the statement
$stmt->close();

echo "1 record added";

$mysqli->close();