How can I select a row from mysql query and save it to variable using 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_arraybut I can’t figure out how to use it. 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. Since you had already called afetchAll()method, you cannot call another fetch/fetchAll method later on as the data will no longer be accessible.In place of
$row = $stmt->fetchAll(PDO::FETCH_OBJ);, iterate over the$resultvariable that you previously hadfetchAll()return into: