I am new to PDO and having trouble placing the results of a fetch into an array.
The following code succeeds in querying the database. However, I would like to place the results into an array so that I can then work with the elements of the array individually. I am not sure what exactly $result
below is. Is it already an array? Or what is it. I think I need to use fetchAll
to get the array. If so, would appreciate proper code to do this. Or if $results
below is already an array, then what is the difference between that and what I would get with fetchAll
?
//USE PDO TO CONNECT TO DBASE
$hostdb = "my host";
$namedb = "mydb";
$passdb = "bypass";
$userdb = "myusername";
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `comments` WHERE `userid` IN(118)";
$result = $conn->query($sql); // THIS WORKS
// $result = $sql->fetchAll(PDO::FETCH_OBJ); //THIS DOES NOT WORK
if($result !== false) {
// Parse the result set
foreach($result as $row) {
echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
}
}
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}