Reputation: 13
Below is the code I have, it was all written in mysql. I am trying to switch to PDO. My question is, what is the equivalent of mysql_result in PDO?
$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');
}
So far, I am only able to execute the $query by doing the following below.
$query = $PDO -> prepare("SELECT id, firstname, lastname FROM table");
$query -> execute();
Upvotes: 1
Views: 6523
Reputation: 6573
Try this...
$query = $PDO->prepare("SELECT id, firstname, lastname FROM table");
$query->execute();
$res = $query->fetchAll(PDO::FETCH_ASSOC);
var_dump($res);
==== update in response to comment ====
$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;
}
Upvotes: 1
Reputation: 2457
As Ian stated above is one way, or if your not utilizing the prepare function then you could just do:
$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";
}
Upvotes: 1