简体   繁体   中英

Pass value from href link to detail page

I have a table that shows all the users. I'd like to put a link around the usernames so when you click on a username it takes you to their profile page.

How do I put the username into a href link and pass it to the detail page?

This is all I have at the minute:

if ($allPlayers > 0 ) {
    while ($allPlayersItem = mysqli_fetch_assoc($playersQuery)) {
        echo "<a href='detailpage.php'>".$allPlayersItem['gamertag']."</a>";
        echo "<br>";
    }
}

You can add the player's gamertag to a query parameter for example:

echo "<a href='detailpage.php?player={$allPlayersItem['gamertag']}'>".$allPlayersItem['gamertag']."</a>";

Then in detailpage.php you can write:

$player = $_GET['player'] ?? '';
if ($player != '') {
     // display player details...
}

Note that if the gamertag value may contain special characters then you should urlencode the value before using it as a parameter ie

echo "<a href='detailpage.php?player=" . urlencode($allPlayersItem['gamertag']) . "'>".$allPlayersItem['gamertag']."</a>";

First of all, I suggest you to split the responsability of getting the data from the DB and the rendering the data. The most common approach for that it could be following the MVC pattern.

Something like:

# Controller/PlayerController
final class PlayerController
{
    public function index(): Response
    {
        $players = [/* list of players to display. From the DB, for example*/];

        return $this->render('player/index.[blade|twig|php]', $players);
    }
}

# Views/player/index.php
<?php foreach ($players as $player): ?>
    <a href='detailpage.php'>" . <?= $player['gamertag']?> . "</a><br>"
<?php endforeach ?>

I recommend you to research and learn more about this topic using google , for exmaple.

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