0

嗨,我想知道如何迁移 mysqli php 文件以使用 PDO。任何人都可以看看我的代码,看看我是否走在正确的轨道上?

这是我的原始(mysqli)代码:

<?php
    // connecting to database
    $conn = new mysqli('xxxxxx', 'xxxxxx', 'password', 'xxxxxx');

    $match_email = 'email';
    $match_passhash = 'passhash';

    if (isset($_POST['email'])) {
        $clean_email = mysqli_real_escape_string($conn, $_POST['email']);
        $match_email = $clean_email;
    }

    if (isset($_POST['passhash'])) {
        $clean_passhash = mysqli_real_escape_string($conn, $_POST['passhash']);
        $match_passhash = sha1($clean_passhash);
    }

    $userquery = "SELECT email, passhash, userlevel, confirmed, blocked FROM useraccounts
                  WHERE email = '$match_email' AND passhash = '$match_passhash'
                  AND userlevel='user' AND confirmed='true' AND blocked='false';";

    $userresult = $conn->query($userquery);
    if ($userresult->num_rows == 1) {
        $_SESSION['authorisation'] = 'knownuser';
        header("Location: userhome.php");
        exit;
    } else {
        $_SESSION['authorisation'] = 'unknownuser';
        header("Location: userlogin.php");
        exit;
    }
?>

这是我将其迁移到 PDO 的尝试:

<?php
    // connecting to database
    $dbh = new PDO("mysql:host=xxxxxx; dbname=xxxxxx", "xxxxxx", "password");

    $match_email = 'email';
    $match_passhash = 'passhash';

    if (isset($_POST['email'])) {
        $clean_email = mysqli_real_escape_string($conn, $_POST['email']);
        $match_email = $clean_email;
    }

    if (isset($_POST['passhash'])) {
        $clean_passhash = mysqli_real_escape_string($conn, $_POST['passhash']);
        $match_passhash = sha1($clean_passhash);
    }

    $userquery = "SELECT email, passhash, userlevel, confirmed, blocked FROM useraccounts
                  WHERE email = ':match_email' AND passhash = ':match_passhash' AND
                  userlevel='user' AND confirmed='true' AND blocked='false';";

    $stmt = $dbh->prepare($query);
    $stmt->bindParam(":match_email", $match_email);
$stmt->bindParam(":match_passhash", $match_passhash);
$stmt->execute();

    $userresult = $conn->query($userquery);
    if ($userresult->num_rows == 1) {
        $_SESSION['authorisation'] = 'knownuser';
        header("Location: userhome.php");
        exit;
    } else {
        $_SESSION['authorisation'] = 'unknownuser';
        header("Location: userlogin.php");
        exit;
    }
?>

我也不确定如何计算 PDO 中返回的行数。

如果有人能够帮助我,那就太好了。

一百万提前谢谢!

4

1 回答 1

0

当使用准备好的语句$stmt->bindValue()/或$stmt->bindParam()您不需要使用 转义值时mysqli_real_escape_string(),PDO 将为您执行此操作。

请记住为该值设置正确的数据类型。这是绑定函数中的第三个参数,默认情况下它是一个字符串,所以你的代码很好。我只会使用bindValue()而不是bindParam()因为您不需要参考。

$stmt->execute()将您准备好的语句作为查询运行。另一个$conn->query()不适用于准备好的语句。它用于原始查询,就像您以前使用 MySQLi 一样。

运行时$stmt->execute(),您的响应将保存在$stmt对象中。对于行数使用$stmt->rowCount().

于 2012-08-20T02:07:17.200 回答