Benjamin Lawson Benjamin Lawson - 6 months ago 11
PHP Question

How to call on a PHP dynamic variable name?

I have 24 pieces of data on an SQL server. When my webpage starts it pulls all this data one at a time from the server and displays it. Looks like this:

$sql = "SELECT `$dateName` FROM `$user` WHERE hour=2";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$hour2 = $row[$dateName];
}
}
$sql = "SELECT `$dateName` FROM `$user` WHERE hour=3";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$hour3 = $row[$dateName];
}
}


etc... until hour 24.

But I think it is better with a for loop. Like this:

for ($x = 1; $x <= 24; $x++) {

$sql = "SELECT `$dateName` FROM `$user` WHERE hour=`$x`";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$hour.$x = $row[$dateName];
}
}
}


I want to call $hour1, $hour2, $hour3. By adding $x to $hour. How do I do this? Thank you so much!

Answer

Instead of generating dynamic variables, I would suggest to create array of $hours.

$hour = array();
for ($x = 1; $x <= 24; $x++) {

    $sql = "SELECT `$dateName` FROM `$user` WHERE hour=`$x`";
    $result = $conn->query($sql);


    if ($result->num_rows > 0) {
         while($row = $result->fetch_assoc()) {
             $hour[$x][] = $row[$dateName];
         }
    }
 }

So that you can access like $hour[1],$hour[2]...etc...

Comments