如何将动态 PHP 变量从一个页面传递到另一个页面?

How do I pass a dynamic PHP variable from one page to another?

我正在创建 2 个网页。第一个将显示项目列表。第二个网页,我想创建一个通用的网页,这样当用户根据所选的项目点击一个项目时,第二个页面将根据项目进行修改。 我只想传递一个字符串变量,从中我可以从数据库中获取其余的东西。就像电子商务网站一样。

有几种方法可以实现您想要的效果。

一些例子:

使用 GET:

您可以使用 link 将变量传递到下一页。

第 1 页:

<a href="yourpage2.php?variable=<?php echo $value; ?>">Page 2</a>

第 2 页:

if(isset($_GET['variable'])) {
    $new_variable = $_GET['variable'];
}

使用POST:

第 1 页:

<form method="POST" action="yourpage2.php">
    <input type="hidden" name="variable" value="<?php echo $value; ?>">
    <input type="submit" value = "Next Page">
</form>

第 2 页:

if(isset($_POST['variable'])) {
   $new_variable = $_POST['variable'];
}

使用 COOKIE:

第1页:

$_COOKIE['variable'] = $value;

第 2 页:

$new_variable = $_COOKIE['varname'];

When using cookies, the variable's value is stored on the client side, opposite of sessions, where the value is stored on the server side.

使用会话:

第 1 页:

$_SESSION['variable'] = $value;

第 2 页:

$new_variable = $_SESSION['variable'];

Notice: When using SESSIONS, do not forget to include/write session_start(); in the start of your page right after your <?php tag on BOTH of your pages.