0

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 ...

4

3 回答 3

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();
于 2013-06-17T21:38:48.187 回答
0

只需将您想要的所有字段放入同一个查询中。

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

并且您需要 fetchAll() 而不是 Igor 所指示的 fetchColumn()。

于 2013-06-17T21:42:50.887 回答
0

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}\n";
于 2013-06-17T21:47:21.600 回答