Question

I have a database of page names on my site, and I'd like to loop through a query and output each of these page names. I've done my query using PDO:

// Site Menu Items
try {
  $mds_system1 = new PDO('mysql:dbname=mds_system;host=127.0.0.1', 'root', '');
} catch (PDOException $ex) {
  echo 'Connection failed: ' . $ex->getMessage();
}

$sql = "SELECT longName, shortName, `position`, standalone FROM `site-menu`";
$sitemenu = $mds_system1->query($sql);

I then loop through the query as so (part of a CMS to edit pages on the site):

    $n=1;
    foreach ($sitemenu as $item) {
        echo "<a href='?page=edit&amp;edit=".$item['shortName']."' target='_self'>";

        if ($n==count($sitemenu)) {
            echo $item['longName']."</a><br />";
        }
        else {
            echo $item['longName']."</a>&nbsp;|&nbsp;";
        }
        $n++;
    }

I'd like there to not be a delimiter after the last result, and according to many examples I've seen, this code should work. However, the "count($sitemenu)" variable is always set to "1", no matter the number of results. Therefore, nothing really happens. Is the code that I'm attempting not possible with PDO?

Was it helpful?

Solution

you forgot one required operation.
beside just query execution, you have to get the actual results using fetchAll() method.
And you will get your desired array.

So, in fact your question has nothing to do with the problem in the title but rather it is basic PDO usage related.

And lack of debugging of course.
As you have to ask the question from the comments yourself, and boil the problem down to the $sitemenu contents.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top