Questions & Answers

String Output for Dynamic Year

I am trying to generate a string like the below for use in MySQL. The output I get seems accurate but when I put the string into the MySQL while loop it wont work. If I manually enter the desired output shown the MySQL query variables for $sales2020, etc work fine. What am I missing?

Desired output:

$sales2020 = $row["2020"];
$sales2021 = $row["2021"];
$sales2022 = $row["2022"];
$sales2023 = $row["2023"];

PHP to Generate the above:

    //Row Strings Generator
    $d = date('Y');
    $sales_year = '';
    for($i = 2020; $i <= $d; $i ++) {
        $sales_year .= '$sales'.$i.' = $row["'.$i.'"];';

The MySQL:

$yearTotals = $db_data->query($yearTotals_sql);
while($row = $yearTotals->fetch_assoc()) {
    $sales_year;  // This does not work for some reason
    // This works if I manually enter it like below.
    //$sales2020 = $row["2020"];$sales2021 = $row["2021"];$sales2022 = $row["2022"];$sales2023 = $row["2023"];
2023-01-18 23:01:03
Why do you need all the $salesXXXX variables? Just use $row[$i]
2023-01-18 23:01:03
Anyway, the syntax for variable variables is ${'sales' . $i}
Answers(0) :