PDO中的mysql_result

时间:2013-10-26 01:27:41

标签: php mysql sql pdo

下面是我的代码,它全部用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();

2 个答案:

答案 0 :(得分: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;
} 

答案 1 :(得分: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";
}