[英]Select row from mysql query and save it to variable
How can I select a row from mysql query and save it to variable using PDO? 如何从mysql查询中选择一行并使用PDO将其保存到变量中? Previously I did it like this
以前我是这样做的
$row = mysql_fetch_array($result);
$ID = $row['ID'];
Now i read from the PHP manual that PDOStatement::fetch()
is alternative to mysql_fetch_array
but I can't figure out how to use it. 现在,我从PHP手册中了解到
PDOStatement::fetch()
可以替代mysql_fetch_array
但是我不知道该如何使用它。 This is what I tried but obviously it doesn't work 这是我尝试过的方法,但显然不起作用
<?php
include 'config.php';
$sql = "select * from table1";
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"items":'. json_encode($result) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
$row = $stmt->fetchAll(PDO::FETCH_OBJ);
$ID = $row['ID'];
?>
If you're using PDO::FETCH_OBJ
, you must use object notation to retrieve elements in the result. 如果使用
PDO::FETCH_OBJ
,则必须使用对象表示法来检索结果中的元素。 Since you had already called a fetchAll()
method, you cannot call another fetch/fetchAll method later on as the data will no longer be accessible. 由于您已经调用了
fetchAll()
方法,因此以后将无法再调用另一个fetch / fetchAll方法,因为将无法再访问数据。
In place of $row = $stmt->fetchAll(PDO::FETCH_OBJ);
代替
$row = $stmt->fetchAll(PDO::FETCH_OBJ);
, iterate over the $result
variable that you previously had fetchAll()
return into: ,遍历您之前具有
fetchAll()
返回的$result
变量:
foreach($result as $row)
{
$ID = $row->ID;
// Etc...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.