0

PHP 7 and MySQL. I want to take a set of labels stored in the database and individually place each label in its own session variable so I can use them as tab labels in my application.

I can retrieve the data and echo it but the corresponding session variables all show a not set status.

<?php

require_once('dbconnect.inc.php');

$_SESSION['histopic'] = "dash";

$numnames = 100;

for ($i = 1; $i <= $numnames; $i++) {

    $stmt = $pdo->prepare('SELECT hislabelsName FROM hislabels WHERE hislabelsID = ?');

    $temp = $i;

    $stmt->execute(array($temp));
    $result = $stmt->fetchALL();

    foreach ($result as $row) {
        $_SESSION['hislabelsName$i'] = $row["hislabelsName"];
    }

    echo $_SESSION['hislabelsName$i'] . "<br>";
    echo $_SESSION['hislabelsName5'] . "<br>";
}

echo $_SESSION['hislabelsName5']; produces an undefined index error.

How do I fix this?

TIA.

MinistryOfChaps
  • 1,458
  • 18
  • 31
SJM
  • 9
  • 1
  • 4
    Try using double quotes instead of single quotes; for example $_SESSION["hislabelsName$i"] – Pieter De Clercq Aug 20 '17 at 14:42
  • @thepieterdc is right. Single quotes support only strings to be wrapped inside it and variable values can't be parsed. – Junaid Aug 20 '17 at 14:45
  • 1
    Possible duplicate of [What is the difference between single-quoted and double-quoted strings in PHP?](https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php) – user3942918 Aug 20 '17 at 15:15
  • Thanks, everyone. It works now! – SJM Aug 20 '17 at 21:11

1 Answers1

0

You have to use double quotes like this:

$_SESSION["hislabelsName$i"] = $row["hislabelsName"];

You also do it like this:

$_SESSION["historylabelsName][$i] = $row["hislabelsName"];

Then to echo either:

echo $_SESSION["hislabelsName5"] or echo $_SESSION["hislabelsName][5];

Chris
  • 4,672
  • 13
  • 52
  • 93
coder_1432
  • 283
  • 2
  • 10