Home > Software design >  link variable id to its profile page
link variable id to its profile page

Time:08-26

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();
?>```

CodePudding user response:

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.

  • Related