2

我正在尝试将所有查询重写为 PDO 格式。目前我正在尝试重写这个函数,但我似乎无法让它工作。

mysql_query 函数

    function checkLogin() {

    $this->sQuery = "SELECT * FROM users 
          WHERE gebruikersnaam='" . mysql_real_escape_string($_POST['gebruikersnaam']) . "'
          AND wachtwoord = '" . sha1($_POST['wachtwoord']) . "'";


    $this->rResult = mysql_query($this->sQuery)
            or die("Er is iets misgegaan " . mysql_error());


    if (mysql_num_rows($this->rResult) == 1) {  // login name was found            
        $this->aRow = mysql_fetch_assoc($this->rResult);
        $_SESSION['gebruiker'] = $this->aRow['voornaam'];

        header("location: dashboard.php");
    }
}

这就是我对 PDO 的了解:

       function checkLoginPDO(){
    $connect = new PDO(host, username, password); // Database Connectie maken (De host, username & password zijn in de config.php aan te passen)
    $sql = "SELECT * FROM users 
          WHERE gebruikersnaam='" . mysql_real_escape_string($_POST['gebruikersnaam']) . "'
          AND wachtwoord = '" . sha1($_POST['wachtwoord']) . "'"; 
    $value = $connect->prepare($sql); //Een variabele aanmaken die de PDO vast houdt. Vervolgens word de code voorbereid door de prepare functie
    $value->execute(); 
    if(mysql_num_rows($value->fetch()) == 1){
        $_SESSION['gebruiker'] = $row['voornaam'];
        header("location: dashboard.php");
    }
}

我在做什么错/忘记了?

提前致谢!

4

4 回答 4

2

它应该是这样的:

function checkLoginPDO(){
    $connect = new PDO(host, username, password); // Database Connectie maken (De host, username & password zijn in de config.php aan te passen)
    // define sql query string with special placeholders in the form of ?
    $sql = "SELECT * FROM users 
      WHERE gebruikersnaam=?
      AND wachtwoord =?";
    // prepare statement based on sql query string
    $statement = $connect->prepare($sql);
    // bind first question mark with value from $_POST, first question mark will be replaced with that value
    $statement->bindParam(1, $_POST['gebruikersnaam']);
    // do the same for second question mark
    $statement->bindParam(2, sha1($_POST['wachtwoord']));
    // execute this prepared statement with binded values
    $statement->execute();
    // fetch row from the result in the form of associated array
    if(($row = $statement->fetch(PDO::FETCH_ASSOC))){
        $_SESSION['gebruiker'] = $row['voornaam'];
        header("location: dashboard.php");
    }
    // free statement memory
    $statement = null;
}

注意:代码未经测试。

编辑,添加解释:使用 PDO 时,您应该使用它处理查询和数据库的方式。使用任何 mysql_* 函数都不是执行此操作的最佳方式。

于 2013-02-27T09:54:38.643 回答
1
  • 首先,确定您想要哪种类型的错误处理。PDO 默认为PDO::ERRMODE_SILENT这意味着您不会收到任何错误。我建议您使用PDO::ERRMODE_EXCEPTION这意味着您需要使用try { ... } catch() { ... }代码周围的块。

  • 其次,在使用 PDO 时,不能使用mysql_*函数。所以使用mysql_real_escape_string是不正确的。此外,因为您使用的是准备好的语句,所以根本不需要任何 SQL 注入保护。但是你需要使用param binding

  • 7号线附近还有一些mysql_query...

  • PDO 没有内置mysql_num_rows功能。您应该COUNT(*)为此在查询中添加一条语句。另请参阅此答案

于 2013-02-27T09:55:26.623 回答
0
function checkLoginPDO(){
$connect = new PDO(host, username, password); // Database Connectie maken (De host, username & password zijn in de config.php aan te passen)
$sql = "SELECT * FROM users 
      WHERE gebruikersnaam=:gebruikersnaam
      AND wachtwoord = :wachtwoord"; 
$value = $connect->prepare($sql);
$value->bind(':gebruikersnaam',$_POST['gebruikersnaam']);
$value->bind(':wachtwoord',sha1($_POST['wachtwoord']));
$value->execute();
$data = $value->fetchAll();
if(count($data) > 0){
    $_SESSION['gebruiker'] = $data[0]['voornaam'];
    header("location: dashboard.php");
}

}

于 2013-02-27T09:58:11.900 回答
0

登录功能现在可以创造奇迹!多谢你们!我刚刚完成了将文件名写入数据库的图像上传脚本。它有效,但它对 sql-injection 之类的东西安全吗?

我目前正在从事我的最后一个研究项目,其中安全性是一个大问题。如果我能够关闭一个通用的安全 CMS,我将获得程序员学位 :)

这是功能:

function uploadImage() {
    $dir = $_SERVER['DOCUMENT_ROOT'] . 'pvb/upload/';
    $allowedExts = array("jpg", "jpeg", "gif", "png");
    $extension = end(explode(".", $_FILES["file"]["name"]));
    if ((($_FILES["file"]["type"] == "image/gif")
            || ($_FILES["file"]["type"] == "image/jpeg")
            || ($_FILES["file"]["type"] == "image/png")
            || ($_FILES["file"]["type"] == "image/pjpeg"))
            && ($_FILES["file"]["size"] < 2000000)
            && in_array($extension, $allowedExts)) {
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        } else {
            if (file_exists($dir . $_FILES["file"]["name"])) {
                echo $_FILES["file"]["name"] . " already exists. ";
            } else {
                move_uploaded_file($_FILES["file"]["tmp_name"], $dir . $_FILES["file"]["name"]);
                $this->createThumbs($dir, $dir . "thumbs/", 100);

                $connect = new PDO(host, username, password); // Database Connectie maken (De host, username & password zijn in de config.php aan te passen)
                $sql = "INSERT INTO afbeeldingen (img_naam) VALUES (:naam)";
                $value = $connect->prepare($sql);
                $value->bindValue(":naam", $_FILES['file']['name'], PDO::PARAM_STR);
                $value->execute();
                $connect = null;
            }
        }
    } else {
        echo "Invalid file";
    }
}
于 2013-02-27T10:22:18.967 回答