Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are several ways to pass a PHP variable from a while loop to the following page:

  1. Using GET or POST method: You can append the variable value to the URL using the GET method or pass it through a form using the POST method. The following code demonstrates how to pass a variable using the GET method:
while ($row = mysqli_fetch_array($result)) {
   $id = $row['id'];
   $name = $row['name'];
   echo "<a href='next_page.php?id=$id'>$name</a>";
}

In the above code, the ID value is appended to the URL, which can be accessed on the next page using the $_GET superglobal.

  1. Using Session variables: You can store the variable value in a session variable and retrieve it on the next page. Here's an example:
while ($row = mysqli_fetch_array($result)) {
   $id = $row['id'];
   $name = $row['name'];
   $_SESSION['id'] = $id;
   $_SESSION['name'] = $name;
   echo "<a href='next_page.php'>$name</a>";
}

In this code, we have stored the ID and name values in session variables, which can be retrieved on the next page using the $_SESSION superglobal.

  1. Using Cookies: You can set a cookie with the variable value and access it on the next page. Here's an example:
while ($row = mysqli_fetch_array($result)) {
   $id = $row['id'];
   $name = $row['name'];
   setcookie('id', $id, time()+3600);
   setcookie('name', $name, time()+3600);
   echo "<a href='next_page.php'>$name</a>";
}

In this code, we have set a cookie with the ID and name values, which can be accessed on the next page using the $_COOKIE superglobal.