1

下面是我的代码,都是用mysql写的。我正在尝试切换到 PDO。我的问题是,PDO 中 mysql_result 的等价物是什么?

$query = "SELECT id, firstname, lastname FROM table";
if($mysql_query = mysql_query($query)){
    $id = mysql_result($mysql_query, 0, 'id');
    $firstname = mysql_result($mysql_query, 0, 'firstname');
    $lastname = mysql_result($mysql_query, 0, 'lastname');
}

到目前为止,我只能通过执行以下操作来执行 $query。

$query = $PDO -> prepare("SELECT id, firstname, lastname FROM table");
$query -> execute();
4

2 回答 2

1

正如 Ian 所说的那样是一种方法,或者如果您不使用准备功能,那么您可以这样做:

$sth = $PDO->query("SELECT id, firstname, lastname FROM table");

if ($sth->rowCount() > 1) {
    // One way to get the results if you have more then one row
    foreach ($sth as $row) {
        echo "ID: ".$row['id']."\n";
        echo "First name: ".$row['firstname']."\n";
        echo "Last name: ".$row['lastname']."\n";
    }
} elseif ($sth->rowCount() == 1) {
    // Or this way if you just have one row
    $result = $sth->fetch(PDO::FETCH_ASSOC);

    echo "ID: ".$result['id']."\n";
    echo "First name: ".$result['firstname']."\n";
    echo "Last name: ".$result['lastname']."\n";
}
于 2013-10-26T01:43:41.097 回答
1

尝试这个...

$query = $PDO->prepare("SELECT id, firstname, lastname FROM table");
$query->execute();
$res = $query->fetchAll(PDO::FETCH_ASSOC);
var_dump($res);

====根据评论更新====

$query = $PDO->prepare("SELECT id, firstname, lastname FROM table");
$query->execute();
$people = $query->fetchAll(PDO::FETCH_CLASS, 'stdClass');
foreach($people as $person) {
    echo 'ID: ' . $person->id . PHP_EOL .
         'First Name: ' . $person->firstname . PHP_EOL .
         'Last Name: ' . $person->lastname . PHP_EOL;
} 
于 2013-10-26T01:33:41.920 回答