Displaying a user profile page PHP

2020-08-04 10:06发布

问题:

I'm currently in the process of making a social network. I'm am displaying all registered users with the following code. Is there a better way of doing this?

<?php 
$query = $db->query("SELECT * from members");

while($r = $query->fetch()) {
    echo '<div class="col-sm-6 col-md-6 col-lg-3 membersGrid">';
    echo '<div class="profileThumb">';
    echo  '<img width="130" height="130" src="'.$r['profile_pic'].'"/><br>';
    echo $r['username'], '<br>';
    echo  $r['country'], '<br>';
    echo '<a class="viewProfile" href="profile.php"><button>View Profile</button></a>';
    echo '</div>';
    echo '</div>';

}
  ?>

I'm trying to create a link to the individual profile pages for each users. Currently each link is within the above while loop, however, I'm a little uncertain of how to link to the relevant profile page. I'm guessing I have to append a variable to the URL. Any guidance would be greatly appreciated.

    echo '<a class="viewProfile" href="profile.php"><button>View Profile</button></a>';

回答1:

It would depend on how your profile.php page is handling the GET variable that determines the profile of the person you are showing. Let's say that the variable is called id and that you have a row in your members table also called id (which acts as the unique key), then your anchor tag would look like:

echo '<a class="viewProfile" href="profile.php?id=' . $r['id']. '"><button>View Profile</button></a>';


回答2:

First retrieve the user_id of the user from the database as you are doing with the query. Then give this id to the profile link as:

echo '<a href="profile.php?userid=' . $user_id . '>Linkname</a>';

Then in profile.php get this variable through:

$id = $_GET['userid'];

This way you can show the relevant user's profile in the profile.php.

Hope you might get the idea to work on.



回答3:

If you are producing a list of links to user profiles then there are a couple of different options:

You can either append a $_GET variable to the end of your link as previously mentioned by Lloyd

echo '<a href="profile.php?if=' . $r['id'] . '">';

or you can send a $_POST variable; the easiest way to do this would be to create a list of forms:

<?php 
$query = $db->query("SELECT * from members");
while($r = $query->fetch()) {
    echo '<div class="col-sm-6 col-md-6 col-lg-3 membersGrid">';
    echo '<div class="profileThumb">';
    echo '<img width="130" height="130" src="'.$r['profile_pic'].'"/><br>';
    echo $r['username'], '<br>';
    echo $r['country'], '<br>';
    echo '<form action="profile.php" method="post">';
    echo '<input type="hidden" value="' . $r['id'] . '" />';
    echo '<input type="submit" value="View Profile" />';
    echo '</form>';
    echo '</div>';
    echo '</div>';
}
?>

Sorry if I've misread your question, hope this helps.