如何将mysqli迁移到pdo

时间:2012-08-20 01:54:36

标签: mysqli

您好我想知道如何迁移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中返回的行数。

如果有人能够帮助我,那将非常棒。

提前一百万谢谢!

1 个答案:

答案 0 :(得分:0)

使用prepared statements$stmt->bindValue()$stmt->bindParam()时,您无需使用mysqli_real_escape_string()转义值,PDO会为您执行此操作。

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

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

运行$stmt->execute()时,您的回复会保存在$stmt对象中。对于行计数使用$stmt->rowCount()