PHP Code to avoid sql injection [duplicate]

非 Y 不嫁゛ 提交于 2020-01-14 07:00:08

问题


Possible Duplicate:
Best way to prevent SQL injection in PHP?

This is my code

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

Please help me in making this code secured so that i can avoid SQL Injection


回答1:


the better approach will be

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

you can use the function below but i/we recommended you to not use function since the mysql_* now anymore maintained and updating by community .

Its for only your knowledge only

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

Good read

Best way to prevent SQL injection in PHP?




回答2:


Well it seems people are down voting you because you have demonstrated little effort in solving your problem. If you want to be safe from injection attacks than you must use either mysqli or PDO APIs with prepared statements. MySQL API will always be susceptible to injection, that's why it's not recommended to use.

It seems like you are at an early stage in your app so I would suggest refactoring to use a better API like MySQLi or PDO




回答3:


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

Filter every input with mysql_real_escape_sting.

If this doesn't work try the deprecated substitute available mysql_real_escape;



来源:https://stackoverflow.com/questions/12550304/php-code-to-avoid-sql-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!