Array to String Conversion PHP

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

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:

$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.


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!