如何在会话中存储值?

时间:2016-07-06 06:26:51

标签: php html

我在php页面上显示用户名作为链接,点击导航到特定用户主页:

$msql=$db->prepare("SELECT * from users where id=? order by id desc");
$msql->bind_param("i",$user_id);
$msql->execute();
$msql = $msql->get_result();
$msql = $msql->num_rows;

while($usercount=$msql->fetch_assoc())
  {
 $Email = $usercount['email'];
  $FirstName = $usercount['first_name'];
  $LastName = $usercount['last_name'];
?>


<strong><a href="?navigate=true" class="post_user" id="post_user" data-emailID="<?php echo $Email; ?>"><?php echo $FirstName.' '.$LastName;?></a></strong>

<?php

}
?>

要点击链接导航到用户主页,我就是这样使用:

<?php

  if(isset($_GET['navigate']) && $_GET['navigate'] == "true"){

      $_SESSION['email'] = $Email;
      header('location: nextpage.php');
  }

?>

所以我的页面看起来像链接

user1
user2
user3
.
.
.
usern

我的问题是每当我点击任何链接时,它总是将第一封电子邮件存储在会话变量中。

所以,如果我输出nextpage.php中的SESSION

echo $_SESSION['email'];

它总是回应第一个链接email

我对此的猜测是因为我使用它的while循环总是拾取第一个链接数据并保持不变,但我的问题是如何获取其他人的数据。我想导航到单击该链接的用户页面,只有在我点击链接时收到正确的电子邮件时才能这样做。

1 个答案:

答案 0 :(得分:2)

正如您所说result.paste(im=img1, box=(0,height2)) 不是主键,我假设您的同一id将包含不同的id,您必须执行以下更改: -

emails

<?php
$msql=$db->prepare("SELECT * from users where id=? order by id desc");
$msql->bind_param("i",$user_id);
$result = $msql->execute(); // assign to a variable
//$msql = $msql->get_result(); //you are over-writing to one variable which is not correct
//$msql = $msql->num_rows; //you are over-writing to one variable which is not correct

while($usercount=$result->fetch_assoc()){
    $Email = $usercount['email'];
    $FirstName = $usercount['first_name'];
    $LastName = $usercount['last_name'];
?>
<strong><a href="?navigate=true&email=$Email" class="post_user" id="post_user" data-emailID="<?php echo $Email; ?>"><?php echo $FirstName.' '.$LastName;?></a></strong> <!-- send mail id to the url too otherwise how's you will get the email id to save it into SESSION-->

<?php } ?>

AND

<?php

    if(isset($_GET['navigate']) && $_GET['navigate'] == "true"){
        $_SESSION['email'][] = $_GET['email']; // assign each mail to SESSION ARRAY not SESSION variable
        header('location: nextpage.php');
    }

?>

注意: - 如果您想在该页面上使用echo "<pre/>";print_r($_SESSION['email']); //to see all emails. ,则必须在session_start();之后的php页面上撰写<?php