Skip to content
Advertisement

Convert MySQL login script to PDO

I’ve written a functional login script using MySQL. However, I’ve now been told that it needs to be done using PDO, and I’ve a functional PDO connection:

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;

However I’ve no idea how to convert the login query to 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.
    }
}

How can I do it?

Advertisement

Answer

To get you started:

$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();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement