使用PDO从MySQL数据库中获取多个变量的最佳方法

Okai, so I am trying to fetch multiple variables from the MySQL Database using PDO and I feel that I have to repeat myself alot in the code. Is there a neater way to write this or a more secure way?

Here is my code for the following example:

    $username = $_SESSION['username'];

    $db = new PDO('mysql:xxxxxxxx;dbname=xxxxxxxxxxxx', 'xxxxxx', 'xxxxxxx');

    // FETCH name VARIABLE
    $fetchname = $db->prepare("SELECT name FROM login WHERE username = :username");
    $fetchname->bindParam(':username', $username, PDO::PARAM_STR, 40);
    $fetchname->execute();
    $myname = $fetchname->fetchColumn();

    // FETCH age VARIABLE
    $fetchage = $db->prepare("SELECT age FROM login WHERE username = :username");
    $fetchage->bindParam(':username', $username, PDO::PARAM_STR, 40);
    $fetchage->execute();
    $myage = $fetchage->fetchColumn();

I wish to avoid having to repeat this FETCH for each variable from the same table...

Have you tried the fetchAll method

// FETCH name VARIABLE
$fetch = $db->prepare("SELECT name, age FROM login WHERE username = :username");
$fetch->bindParam(':username', $username, PDO::PARAM_STR, 40);
$fetch->execute();
$login = $fetch->fetchAll();

Just put all the fields you want into the same query.

$fetchAgeName = $db->prepare("SELECT name, age FROM login WHERE username = :username");

And you need fetchAll() instead of fetchColumn() as indicated by Igor.

Something like this perhaps?

$sth = $db->prepare("SELECT name, age, whatever FROM login WHERE username = :username");
$sth->bindParam(':username', $username, PDO::PARAM_STR, 40);
$sth->execute();
$login = $sth->fetchObject(); // fetches only the first row as an object
print "Hello {$login->name}, you are {$login->age} old. {$login->whatever}
";