一尘不染

PHP代码避免sql注入

sql

这是我的代码

$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注入


阅读 120

收藏
2021-05-16

共1个答案

一尘不染

更好的方法是

  1. mysqli_query()
  2. PDO :: query()

您可以使用下面的功能,但我/我们建议您不要使用该功能,因为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 ;
}

好读

防止PHP中进行SQL注入的最佳方法?

2021-05-16