简体   繁体   中英

PHP Session value different in the same block of code

Ok, so I am using PHP to interface with MySQL . Here's my code:

<?php                           
        include 'php/connect.php';
        $string = "SELECT * FROM games";
        $query = mysqli_query($conn, $string);
        while ($row = mysqli_fetch_array($query)){
          $result = "<option id='pkey' style='background-color:#E3D1B9'";
          $result .=  "<value='".$row['pkey']."'>";
          $_SESSION['keyVal'] = $row['pkey'];
          $result .=  $row['Opponent'];
          $result .= "</option>";
          echo $result;
        }                           
?>

This is embedded inside the HTML. The problem is, that under the line

$result .= "<value='".$row['pkey']."'>";

$row['pkey'] is right. However, when I assign it to the Session value, it outputs as the total number of rows in the table, which is 12. It always assigns 12 to the Session value. Any idea how to fix this?

You can convert in to array:

$_SESSION['keyVal'][] = $row['pkey'];

Then for fetching the session value you need to do like this

<?php echo $_SESSION['keyVal'][0]; //this is for first row ?>

You can try the below code:

$result = "<option id='pkey' style='background-color:#E3D1B9'";
          $result .=  "value='".$row['pkey']."'>";
          $result .=  $row['Opponent'];
          $result .= "</option>";
          $_SESSION['keyVal'][] = $row['pkey'];
          echo $result;

Modify your html structure also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM