将mysql登录脚本转换为PDO

时间:2012-04-27 11:41:15

标签: php mysql login pdo

我用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.
}
}

非常感谢任何见解/帮助

3 个答案:

答案 0 :(得分:6)

浏览PDO manual。但是,为了让你开始:

$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();

答案 1 :(得分: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;
}

答案 2 :(得分:-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';
}?>