-1

The following SQL PHP code shows count of country from database and displays it in a table. Here is the code

foreach($dbh->query('SELECT country,COUNT(*)
FROM data_able
GROUP BY country') as $row) {    $array = array();
echo "<tr>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['COUNT(*)'] . "</td>";
echo "</tr>";
}
Here is the result

Here is the result

I would like to use the data as $country1 and $count1. For example $country1 will output "Andorra" and $country5 will be "India". and $count5 should give "25" as result. How can I do that ?

Shami p
  • 3
  • 1
  • 1
    You _shouldn't_ do that, because "numbered" variable names are bad. Use an array instead. – CBroe Apr 28 '22 at 10:24

1 Answers1

0

Here is an example how to declare variables dynamicly:

$array = ['1', '2', '3', '4', '5'];

foreach ($array as $i) {
    ${'country' . $i} = $i;
}

echo $country2;

You just need to iterate through your query results with keeping some index on variable suffix (in your case a number).

// create a dynamic variables
$result = $dbh->query('SELECT country,COUNT(*) FROM data_able GROUP BY country');
$i = 1;
foreach ($result as $row) {
    ${'country' . $i} = $row['country'];
    ${'count' . $i} = $row['COUNT(*)'];
    $i++;
}

// example how to use them
$i = 1;
foreach($result as $row) {
    $array = array();
    echo "<tr>";
    echo "<td>" . ${'country' . $i} . "</td>";
    echo "<td>" .${'count' . $i} . "</td>";
    echo "</tr>";
    $i++;
}
Eddy
  • 593
  • 8
  • 22
  • it will be so great if you can show a real example. I have no idea what to do with `$i`, I am new with these... – Shami p Apr 28 '22 at 10:28
  • @Shamip I've edited the post, check if the code suits your requirements – Eddy Apr 28 '22 at 10:48