dongyan5141 2013-04-13 00:05
浏览 23

将“首字母”html标签显示给MySQL查询结果

After much tinkering, I have managed to get my code to work where the results are grouped together by the first letter with that first letter being displayed also as shown below:

-A-
Alton Towers

-C-
Cedar Point
Chessington

etc.

I have turned those letter headings into HTML anchors. What I'm trying to do now is run similar code that just displays the first letters in a line at the top of page which are links to each anchor. I can't get the code to work. If I duplicate the code and modify it just to show letters, the original query list doesn't display. Can someone help? Below is the code used to display the query results with the letter headings.

try
{
$sql = 'SELECT park_id, name, town, state, country
FROM tpf_parks ORDER BY name ASC';
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$error = 'Error fetching parks: ' . $e->getMessage();
//include 'error.html.php';//
exit();
}


$name = '';


foreach($result as $key=>$row){
    if(substr($row['name'],0,1)!=$name) echo '<br /><br /><h1>-<a name="'.substr($row['name'],0,1).'">'.substr($row

['name'],0,1).'-</h1></a>';
    $name = substr($row['name'],0,1);

    echo "<a href='park.php?park_id=".$row['park_id']."'>

<h2>".$row['name']."</h2>
<h3>".$row['town'].", ".$row['state'].", ".$row['country']."</h3></a><hr>";


}
  • 写回答

1条回答 默认 最新

  • dongyoulou4829 2013-04-13 00:11
    关注

    Your first time you loop through it doesn't automatically reset your pointer on the result set. So when you try to access it the 2nd time, it's empty/at the end of the set. You should read up on how the result PDOStatement object works.

    Here is a similar question that is going to give you an idea of how to solve this.

    评论

报告相同问题?

悬赏问题

  • ¥20 steam下载游戏占用内存
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系