This question already has an answer here:
I want to use a function inside my loop, in order to print my data in a nice format into my table.
$pdo = Database::connect();
$sql = 'SELECT * FROM data ORDER BY id ASC';
foreach ($pdo->query($sql) as $row) {
function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824) {
$bytes = number_format($bytes / 1073741824, 2).' GB';
} elseif ($bytes >= 1048576) {
$bytes = number_format($bytes / 1048576, 2).' MB';
} else {
$bytes = '0 bytes';
}
return $bytes;
}
$bytes = $row['fileSize'];
formatSizeUnits($bytes);
echo('<td>'.$bytes.'</td>');
}
But now I get only the first entry of the database table. How can I get this work?
</div>
Using and declaring your function are two different things. You only need to declare your function once. It throws an error because it is trying to re-declare it in the next loop.
Like this:
$pdo = Database::connect();
$sql = 'SELECT * FROM data ORDER BY id ASC';
foreach ($pdo->query($sql) as $row) {
$bytes = $row['fileSize'];
formatSizeUnits($bytes);
echo('<td>'.$bytes.'</td>');
}
function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824) {
$bytes = number_format($bytes / 1073741824, 2).' GB';
} elseif ($bytes >= 1048576) {
$bytes = number_format($bytes / 1048576, 2).' MB';
} else {
$bytes = '0 bytes';
}
return $bytes;
}
Also regarding your question:
You are not passing the $bytes to formatSizeUnits()
by reference, but it is returning the value, you need to overwrite it.
$bytes = formatSizeUnit($bytes);
You can't declare a function in loop. Instead using it in loop define it outside the loop and call in loop once only