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

时间:2013-06-17 21:35:15

标签: php mysql fetch

Okai,所以我试图使用PDO从MySQL数据库中获取多个变量,我觉得我必须在代码中重复自己。是否有更简洁的方式来写这个或更安全的方式?

以下是我的代码:

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

我希望避免为同一个表中的每个变量重复此FETCH ...

3 个答案:

答案 0 :(得分:0)

您是否尝试过fetchAll方法

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

答案 1 :(得分:0)

只需将所需的所有字段放入同一查询中即可。

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

你需要fetchAll()而不是Igor所指示的fetchColumn()。

答案 2 :(得分:0)

或许这样的事情?

$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}\n";