-1

Currently having an issue with PDO im new to it also (which doesn't help)

this is the current segment of my code

> try{
$sql  = $conn->prepare(" SELECT Channel_Location FROM channels)
ORDER BY RAND()
limit 5");
$sql->execute(array(':Location' => ''));
$row = $sql->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}
$conn =  null; 

I'm basically trying to connect to the database and pull 5 random results from the table Channel_Location but i'm receiving a error Object of class PDOStatement could not be converted to string and i was wondering how i'd solve this by putting the 5 results it returns in to an array?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 1
    You have to remove parenthesis after `channels` in query; in the query there are not `:Location` to bind, you can't echo `$sql` because it is an object, not a string: simply echo `$e->getMessage` – fusion3k Feb 23 '16 at 18:31

2 Answers2

1
   try{    
    $sql  = $conn->prepare("SELECT Channel_Location FROM channels ORDER BY RAND()
    limit 5");
    $sql->execute();
    $row = $sql->fetch(PDO::FETCH_ASSOC);
   }
   catch(PDOException $e)
   {
        echo $e->getMessage();
   }
   $conn =  null; 
Keyne Viana
  • 6,194
  • 2
  • 24
  • 55
-1
<?php
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>";
}

Will retrieve the information you want and display them on your page with a new line between each (:

Your request were incorrect and you did not had to put prepare / execute since you were not using any parameter, a simple queryis enough here.

LoïcR
  • 4,940
  • 1
  • 34
  • 50