link variable id to its profile page

Issue

I have a page that shows some of the information in the database. I’d like to add a link in each row (like making the first name a link) that I can click on that brings me to a page that shows the rest of that row’s info (like a profile page). I’m thinking of making a link that passes the id to the profile page so that the profile page can gather the info.

I’m sure this is simple, but I’m just not getting it. How do I make the link show up in each row that sends only that row’s id number? Because I’d rather not have to go into each row and make a special link.

Here is the code I have:


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}


$sql = "SELECT id, FirstName, LastName, Phone, Email FROM Contacts";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. "
 - Name: " . $row["FirstName"]. " 
" . $row["LastName"]. " 
" . $row["Phone"]. " 
" . $row["Email"]. " <br>";
  }
} else {
  echo "0 results";
}

$conn->close();
?>```

Solution

Based on your example you could do this:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


$sql = "SELECT id, FirstName, LastName, Phone, Email FROM Contacts";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"] . " - Name: <a href='profile.php/?id=" . $row["id"] . "> " . $row["FirstName"] . "</a> " . $row["LastName"] . " " . $row["Phone"] . " " . $row["Email"] . " <br/>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>

That profile.php page would check if the id is set with isset and query the data based on id simular to this: PHP & MYSQL: Select from where id=$id

Not tested and make sure to sanitize any user-generated variables.

Answered By – bbaskets

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published