简体   繁体   中英

displaying 'first letter' html tags to a MySQL query result

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>";


}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM