drq22639 2011-11-23 09:12
浏览 35
已采纳

查询结果中的最后一项 - PHP

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?

  • 写回答

1条回答 默认 最新

  • douxun1934 2011-11-23 09:31
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏