pdo - Array to String Conversion PHP -


so title says i'm having issue when trying display 5 results sql query don't know how convert them array,

# collection of sql  try {     $sql = $conn->query("select channel_location channels     order rand()     limit 5"); } catch(pdoexception $e) {     echo $sql . "<br>" . $e->getmessage(); }  foreach($sql->fetchall(pdo::fetch_assoc) $c) {     echo $c . "<br>"; }    $conn =  null; 

i can't work out how display results, displays 1 result if change foreach($sql->fetchall(pdo::fetch_assoc) $c) { foreach($sql->fetch(pdo::fetch_assoc) $c) { need display each result

$sql = "select channel_location channels order rand() limit 5"; $channels = $conn->query($sql)->fetchall(pdo::fetch_column);  foreach($channels $c) {     echo $c . "<br>"; } 

your main problem trying use variable knowing nothing of type. goes both $sql (which misnamed) , fetchall result. supposed know variable type beforehand, either manual or quick test. $sql not contain sql string , cannot echo out. fetchall result contains nested array, means when iterate over, still have array item, cannot echo directly well. test variable , see whether can echo out, use var_dump() in case of trouble.

to solve numerous problems have

  • name variables (to distinguish sql query statement)
  • get rid of try catch (as php report error you)
  • use pdo::fetch_column instead of pdo::fetch_assoc give desired result type - single-dimensioned atrray.

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -