[英]mysql_result in PDO
Below is the code I have, it was all written in mysql. 下面是我拥有的代码,它们都是用mysql编写的。 I am trying to switch to PDO.
我正在尝试切换到PDO。 My question is, what is the equivalent of mysql_result in 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');
}
So far, I am only able to execute the $query by doing the following below. 到目前为止,我只能通过执行以下操作来执行$ query。
$query = $PDO -> prepare("SELECT id, firstname, lastname FROM table");
$query -> execute();
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;
}
As Ian stated above is one way, or if your not utilizing the prepare function then you could just do: 正如上面伊恩(Ian)所述,这是一种方法,或者,如果不使用prepare函数,则可以执行以下操作:
$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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.