I'm running out of options here and I'm not sure what I'm doing wrong. I want to automate the extraction of data from a table and paginate in the process. the code works flawlessly on its own, but as soon as I make it part of a function (to automate the process), it breaks down. I can't seem to be able to "extract" the data from within the function. What I expect is that once I run the function, I can access the results using the $result
var, but this doesn't work. What am I doing wrong? The page where I'm trying to render the output is included in the page where I run the function.
function generateDataTable(string $table) {
global $PDO;
if(isset($_GET['page']) && !empty($_GET['page']) && ctype_digit($_GET['page'])) { $pageNumber = $_GET['page']; } else { $pageNumber = dataPageNumber; }
if(isset($_GET['list']) && !empty($_GET['list']) && ctype_digit($_GET['list'])) { $listnumber = $_GET['list']; } else { $listNumber = dataListNumber; }
if(!empty($_GET['sortby']) && ctype_alnum($_GET['sortby'])) { $sortBy = $_GET['sortby']; } else { $sortBy = 'id'; }
if(!empty($_GET['sortorder']) && ctype_alnum($_GET['sortorder'])) { $sortOrder = $_GET['sortorder']; } else { $sortOrder = 'ASC'; }
$rowsCount = getRowsCount($table);
$lastPage = ceil($rowsCount/$listNumber);
if ($pageNumber > $lastPage) { $pageNumber = $lastPage; }
if ($pageNumber < 1) { $pageNumber = 1; }
$rowsLimitLow = ($pageNumber - 1) * $listNumber;
$rowsLimitHigh = $listNumber;
$query = $PDO->prepare("SELECT * FROM $table ORDER BY $sortBy $sortOrder LIMIT $rowsLimitLow, $rowsLimitHigh");
$query->execute();
$result = $query->fetchAll();
return $result;
}
this is the page where I run the function and I include a view page (a template) where I'm trying to access the results.
generateDataTable('carrier');
include(DIR_ROOT.'/views/data/default.php');
this is how I'm trying to access the results:
<?php
foreach($result as $item) {
echo '<tr>
<td><input type="checkbox" value="'.$carrier['id'].'"></td>
<td class="expand"><a href="index.php?module=data&action=view&carrier='.$item['id'].'">'.$item['name'].'</a></td>
<td>'.$item['iata_code'].'</td>
<td>'.$item['icao_code'].'</td>
<td>'.$item['country'].'</td>
</tr>';
}
?>
I know that it has to do with the scope of my variables, but I tried everything and it still doesn't work. the other similar questions had some answers, but different situations. I tried declaring $results[]
and creating an array with all columns like this:
$results[] = array($result['id'], $result['name'] etc)
but this failed too. Any thoughts?
You need to assign the return value of the function to the variable:
$result = generateDataTable('carrier');