0

我有两个问题

  1. 下面的代码是练习反对 SQL 注入的好方法吗(它似乎可以作为插入方法工作)

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

    if (!mysqli_query($query,$link))
    {
        die('Error: ' . mysqli_error());
    }
    

这是完整的例子:

<?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);
?>
4

1 回答 1

1

是的,对于 SQL 查询中的动态值,使用绑定参数是防止 SQL 注入的好方法。有关 SQL 注入的更多信息,您可能会喜欢我的演示SQL 注入神话和谬误

没错,调用 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();
于 2012-12-09T19:37:26.260 回答