SoFunction
Updated on 2025-04-09

An example of using PHP to realize ODBC data pagination display

$pagesize = 2; //One page displays the number of records

$con = odbc_connect("access_test","","",SQL_CUR_USE_ODBC) or die("Unable to connect to ODBC data source access_test"); //Connect an ODBC data source
$sql = "select count(*) as total from test"; // Get the total number of records SQL statement
$rst = odbc_exec($con,$sql) or die("$sql query error"); //Execute SQL statement to get the total number of records
$recordcount = odbc_result($rst,1); //Get the total number of records, you can also use $recordcount = odbc_result($rst,"total");
odbc_free_result($rst); //Release resources

$pagecount = bcdiv($recordcount+$pagesize-1,$pagesize,0); // Calculate the total number of pages

if(!isset($page)) $page = 1; //If the display page number is not specified, the default is to display the first page
if($page<1) $page = 1; //If the page number is smaller than 1, the first page will be displayed
if($page>$pagecount) $page = $pagecount; //If the page number is larger than the total number of pages, the last page will be displayed

if($page>0){ //The page number is larger than 0, indicating that there is data
echo '>> Pagination ';
echo '<a href="' . $PHP_SELF . '?page=1">Home</a> ';
   if($page>1){
echo '<a href="' . $PHP_SELF . '?page='. ($page-1) . '">Previous page</a> ';
   }
   else{
echo 'Previous page ';
   }
   if($page<$pagecount){
echo '<a href="' . $PHP_SELF . '?page='. ($page+1) . '">Last Page</a> ';
   }
   else{
echo 'Last page';
   }
echo '<a href="' . $PHP_SELF . '?page=' . $pagecount . '">Last Page</a> ';
echo 'Page: ' . $page . '/' . $pagecount . 'Page ';
echo $pagesize . 'bar/page ';
echo 'Total' . $recordcount . 'bar ';

$sql = "select * from test"; // Get data SQL statement
$rst = odbc_exec($con,$sql) or die("$sql query error"); //Execute the SQL statement to get data

$fieldcount = odbc_num_fields($rst); //Get the total number of fields

   echo '<table border="1" cellspacing="0" cellpadding="0">';
   echo '<tr>';
   for($i=1;$i<=$fieldcount;$i++){
echo '<th>' . odbc_field_name($rst,$i) . '</th>'; //Show the $i field name
   }
   echo '</tr>';
   $rowi = ($page-1)*$pagesize+1;
   for($i=0;$i<$pagesize;$i++){
      echo '<tr>';
      if($rowi>$recordcount){
         for($j=0;$j<$fieldcount;$j++){
            echo '<td>&nbsp;</td>';
         }
      }
      else{
         odbc_fetch_into($rst,$rowi,&$row);
         for($j=0;$j<$fieldcount;$j++){
            $field = $row[$j];
            if($field=='') $field = '&nbsp;';
            echo '<td>' . $field  . '</td>';
         }
         $rowi = $rowi+1;
      }
      echo '</tr>';
   }
   echo '</table>';

odbc_free_result($rst); //Release resources
}
else{
echo "No data";
}

odbc_close($con); //Close the connection and release the resource
?>