Joy
Joy

Reputation: 135

Pass the variable to next page PHP

i am trying to pass the variable to next page via session using PHP. below code save the last value . i want to pass the 'name' when user clicks on "More Info " link,there i will display more information about clicked Name.

<?php while ($r = $q->fetch()):
 $city=$r['city'];
 $phone=$r['phone'];
 $name=$r['name'];
 if (session_status() == PHP_SESSION_NONE) {
   session_start();
  }
 $_SESSION['name'] = $name;
 $_SESSION['phone'] = $phone;
  $_SESSION['city'] = $city;

 ?>
        <tr>
       <td><?php echo (++$i); ?></td>
            <td><?php echo htmlspecialchars($name) ?></td>
            <td><?php echo htmlspecialchars($phone); ?></td>
            <td><?php echo htmlspecialchars($city); ?></td>
      <td> <a href="more_info.php" >More Info</a></td>
        </tr>
    <?php endwhile; ?> 

Upvotes: 0

Views: 135

Answers (1)

Rahul
Rahul

Reputation: 1615

first you need to do put session_start() top of the script.and always remember $_SESSION is super global variable.no need to pass here to access session variable.simply you can access like this.

echo $_SESSION['name'];

Note:make sure session_start() should be top of the script.

if you really want to pass variable one page to another page.do something like below

<td> <a href="more_info.php?name=<?php echo $_SESSION['name']; ?>" >More Info</a></td> 

And your more_info.php.

if (isset($_GET['name'])) {
    $name=$_GET['name'];
    echo $name;
}

given answer could be solve the OP problem but.this is not good habit to use session in while loop.because you are trying to insert name in session but name could be different.i recommend to you try something like this.

Remove:

if (session_status() == PHP_SESSION_NONE) {
   session_start();
  }
 $_SESSION['name'] = $name;
 $_SESSION['phone'] = $phone;
  $_SESSION['city'] = $city;

And pass the variable like this.

<td> <a href="more_info.php?name=<?php echo $name; ?>" >More Info</a></td> 

Upvotes: 2

Related Questions