0

So as the title says i'm having an issue when trying to display the 5 results from my sql query i don't know how to convert them to an array,

# Collection of SQL 
try {
    $sql = $conn->query("SELECT Channel_Location FROM channels
    ORDER BY RAND()
    Limit 5");
} catch(PDOException $e) {
    echo $sql . "<br>" . $e->getMessage();
}

foreach($sql->fetchAll(PDO::FETCH_ASSOC) as $c) {
    echo $c . "<br>";
}
   $conn =  null;

I can't work out how to display the results, it displays one result if i change foreach($sql->fetchAll(PDO::FETCH_ASSOC) as $c) { to foreach($sql->fetch(PDO::FETCH_ASSOC) as $c) { but i need it to display each result

1 Answers1

2
$sql = "SELECT Channel_Location FROM channels ORDER BY RAND() Limit 5";
$channels = $conn->query($sql)->fetchAll(PDO::FETCH_COLUMN);

foreach($channels as $c) {
    echo $c . "<br>";
}

Your main problem is that you are trying to use a variable knowing nothing of its type. It goes both for $sql (which is also misnamed) and for the fetchAll result. You are supposed to know the variable type beforehand, either from the manual or from a quick test. $sql does not contain an SQL string and you cannot echo it out. the fetchAll result contains a nested array, means when you iterate it over, you still have an array as an item, which you cannot echo directly as well. To test a variable and to see whether you can echo it out, always use var_dump() in case of trouble.

To solve all the numerous problems you have to

  • name your variables properly (to distinguish an SQL query from a statement)
  • get rid of try catch (as PHP will already report an error for you)
  • use PDO::FETCH_COLUMN instead of PDO::FETCH_ASSOC which will give you the desired result type - a single-dimensioned atrray.
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345