PHP代码,以避免SQL注入[复制](PHP Code to avoid sql injection

2019-09-22 20:09发布

可能重复:
最好的防止SQL注入的PHP的方式?

这是我的代码

$user_name = "admin";
$password = "123456";
$database = "jbit";
$server = "localhost";
$id = $_POST['id'];
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);

if ($db_found) {

$SQL = "SELECT * FROM jbit WHERE htno='$id'";
$result = mysql_query($SQL);
$sum = "SELECT htno, SUM(tm) AS tech, ROUND(SUM(tm)/7.5, 2) AS divi, SUM(credits) AS cred , SUM(CASE WHEN credits <= 0 THEN 1 ELSE 0 END) AS log,
SUM(CASE WHEN credits > 0 THEN 1 ELSE 0 END) AS pass, SUM(CASE WHEN em >= 0 THEN 1 ELSE 0 END) AS atm, SUM(CASE WHEN em >= -2 THEN 1 ELSE 0 END) AS tot
FROM jbit WHERE htno='$id'";
$result1 = mysql_query($sum);

请帮我进行这项代码保护,以便我能避免SQL注入

Answer 1:

更好的方法将是

  1. mysqli_query()
  2. PDO ::查询()

您可以使用以下的功能,但我/我们建议您不要使用功能,因为mysql_*现在了维护和更新社区。

它只有你的知识只

 $id = mysql_prep($_POST['id']);


function mysql_prep($value)
{
    $magic_quotes_active = get_magic_quotes_gpc();
    $new_enough_php = function_exists("mysql_real_escape_string"); // i.e. PHP >= v4.3.0
    if ($new_enough_php) { // PHP v4.3.0 or higher
        // undo any magic quote effects so mysql_real_escape_string can do the work
        if ($magic_quotes_active) {
            $value = stripslashes($value);
        }
        $value = mysql_real_escape_string($value);
    } else { // before PHP v4.3.0
        // if magic quotes aren't already on then add slashes manually
        if (!$magic_quotes_active) {
            $value = addslashes($value);
        }
        // if magic quotes are active, then the slashes already exist
    }
    return  $value ;
}

好读

最好的防止SQL注入的PHP的方式?



Answer 2:

那么它似乎人们都反对投票你,因为你已经解决您的问题表现出一点力气。 如果你想从注入攻击安全比你必须使用两种库MySQLi或PDO API的准备语句 。 MySQL的API总是容易受到注射,这就是为什么它不推荐使用。

好像你是在你的应用的早期阶段,因此我建议重构使用像一个更好的API 库MySQLi或PDO



Answer 3:

$id = mysqli_real_escape_string(($_POST['id']));

滤波器mysql_real_escape_sting每个输入。

如果这不起作用尝试弃用替补可用mysql_real_escape;



文章来源: PHP Code to avoid sql injection [duplicate]