再次保护SQL注入

时间:2014-10-30 18:40:11

标签: php mysql sql class sql-injection

首先是我的代码:

DatabaseClass:

    <?php
class Database{

     function getMysqli(){
        $mysqli = new mysqli( HOST, DBUSER, DBPASSWORD, DATABASE );
        if (mysqli_connect_errno()) {
                        printf("Connect failed: %s\n", mysqli_connect_error());
                        exit();

                    }
                    return $mysqli;
        }
}
?>

UserClass的:

    <?php

class UserClass extends Database{


    function getUserIDByUsernameAndPass($user,$pass){
            $mysqli = $this->getMysqli();
             $query = "select UserID FROM users WHERE Username='$user' AND Password = '$pass'";

            if ($result = $mysqli->query($query)) {

                /* fetch associative array */
               while($r = mysqli_fetch_assoc($result)) {
                    $rows[] = $r;
                }

                $result->free();

            }
            return $rows[0]['UserID'];
    }

}


?>

登录:

<?php
require_once("../../define/index.php");
require_once("../../require/db.php");
require_once("../../class/UserClass.php");

$user = new UserClass();
$uid = $user->getUserIDByUsernameAndPass($_POST['user'],md5($_POST['password']));


?>

这是否已经受到SQL注入的保护?如果不是,我该怎么做(mysql_real_escape_string()),说他需要一个数据库连接。

如果我将UserClass更改为:

 <?php

    class UserClass extends Database{


        function getUserIDByUsernameAndPass($user,$pass){
                $mysqli = $this->getMysqli();
                $user = mysql_real_escape_string($user);
                 $query = "select UserID FROM users WHERE Username='$user' AND Password = '$pass'";

                if ($result = $mysqli->query($query)) {

                    /* fetch associative array */
                   while($r = mysqli_fetch_assoc($result)) {
                        $rows[] = $r;
                    }

                    $result->free();

                }
                return $rows[0]['UserID'];
        }

    }


    ?>

脚本给了我这个失败:

警告:mysql_real_escape_string():第186行/mounted-storage/home140/sub022/sc86726-PUZQ/new/class/UserClass.php中没有此类文件或目录

警告:mysql_real_escape_string():无法在第186行的/mounted-storage/home140/sub022/sc86726-PUZQ/new/class/UserClass.php中建立指向服务器的链接

谢谢你的回答, 问候 mistermm

0 个答案:

没有答案