Search code examples
phpsqlnumber-formatting

php sql formatting SELECT columns numbers


I am retrieving various columns from an SQL table and some of those are numeric or currency, in a sample let’s say:

$sql="SELECT id_column, event_column, amount_column FROM table1";

Then I show them using that:

$result = mysqli_query($conn,$sql);

echo "<table border='1'>
        <tr>
          <th>id</th>
          <th>event time</th>
          <th>amount</th>
        </tr>";

while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
      echo "<td>" . $row[' id_column '] . "</td>";
      echo "<td>" . $row[' event_column '] . "</td>";
      echo "<td>" . $row[' amount_column '] . "</td>";
    echo "</tr>";
}

echo "</table>";

Is it possible to change the format numbers get out in amount_column?

I saw should be possible to use a command to change a single number data the way I wuold like - number_format($number, 2, ',', '.') – but this seems not to apply for entire columns

What I do need is using comma for decimal under one (yy) and point for others grouped by 3 (x.xxx) thousands, something like xx.xxx.xxx,yy

Does some one have any suggestion? (including how to change the settings in PHP or SQL by the moment when I entry the data via form those have a comma instead of point for decimal but SQL save them in a different way – UK/USA decimal punctuation I guess while I need EU Italian/Germany punctuation or at least the ISO standard using comma for decimal and space for each group of three numbers).


Solution

  • Correct answer is my comment:

    echo "<td>" . number_format($row['amount_column'], 2, ',', ' ') . "</td>";
    

    You can not do:

    $row[' amount_column ']
    

    Spacing for array index count!

    here is a proof https://ideone.com/FtPEc6

    So technically the answer you've approved - is wrong.