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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)