0

我使用 MySQL 编写了一个功能登录脚本。但是,我现在被告知需要使用 PDO 完成,并且我有一个功能性 PDO 连接:

function getConnection()
{
    $userName = '*****';
    $password = '*****';
    $dbname = '******';
    $db = new PDO("mysql:host=localhost;dbname=$dbname", $userName, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $db;

但是我不知道如何将登录查询转换为 PDO。

if (isset($_REQUEST['attempt']))
{
    $user = $_POST['user'];
    $password = $_POST['password'];

    $qry = mysql_query
        ("SELECT *
          FROM subscriber
          WHERE email = '$user'
          AND password = '$password'")
        or die(mysql_error());

    $total = mysql_num_rows($qry);

    if ($total > 0)
    {
        session_start();
        $_SESSION['user'] = 'yes';
        header('location: account.php');
        exit;
    }
    else
    {
        // Do nothing.
    }
}

我该怎么做?

4

3 回答 3

6

为了让你开始:

$db = getConnection();
$stmt = $db->prepare("
    SELECT * FROM subscriber WHERE email = :email AND password = :password
");
$stmt->bindParam(":email"   , $user    );
$stmt->bindParam(":password", $password);
$stmt->execute();
$total = $stmt->rowCount();
于 2012-04-27T11:44:40.350 回答
1

非臃肿版:

$stm = $pdo->prepare("SELECT * FROM subscriber WHERE email = ? AND password = ?");
$stm-> execute($_POST['user'], $_POST['password']);
if ($id = $stm->fetchColumn()) {
    session_start();
    $_SESSION['user'] = $id;
    header('location: account.php');
    exit;
}
于 2013-03-16T08:33:34.280 回答
-1

如果您不想使用 bindParam,也可以使用此示例。但我从@eggyal 的回答中提取了它。非常感谢eggyal。

<?php session_start();
    include_once('pdo.inc.php');

    $username = (isset($_POST['username']))? trim($_POST['username']): '';
    $password = (isset($_POST['password']))? $_POST['password'] : '';
    $pas = md5($password);
    $redirect = (isset($_REQUEST['redirect']))? $_REQUEST['redirect'] :
        'view.php';
    $query = ("SELECT username FROM site_user WHERE username=:username
              AND password =:password");
    $query_login = $con->prepare($query);
    $query_login->execute(array(
        ':username'=>$username,
        ':password'=>$pas));
    $result = $query_login->rowCount();

    if($result>0)
    {
        $_SESSION['username'] = $username;
        $_SESSION['logged'] = 1;
        echo "success";
    }
    else {
        // Set these explicitly just to make sure
        echo 'User name invalid';
    }
?>
于 2013-03-16T08:16:43.903 回答