Ask Your Question
1

How can a PHP variable from a while loop be passed to the following page?

asked 2023-04-28 21:40:50 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-04-28 21:41:02 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-28 21:40:50 +0000

Seen: 16 times

Last updated: Apr 28 '23