PHP Code

General discussion on technical and managerial topics
no avatar
mattnmel1972
 
Posts: 1
Joined: Wed May 22, 2013 3:27 am

PHP Code

by mattnmel1972 » Wed May 22, 2013 4:24 am

Hi
I'm new to this, and was hoping someone may be able to help me, I have a mysql database with 4 fields "id, date, name, comment"
I have the following php file:

Code: Select all
<html>
<head>
<title>Paging Using PHP</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'USERNAME';
$dbpass = 'PASSWORD';
$rec_limit = 5;

$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('DATABASE_NAME');
/* Get total number of records */
$sql = "SELECT count(id) FROM comments ";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
$rec_count = $row[0];

if( isset($_GET{'page'} ) )
{
   $page = $_GET{'page'} + 1;
   $offset = $rec_limit * $page ;
}
else
{
   $page = 0;
   $offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);

$sql = "SELECT * FROM comments ORDER BY id DESC";
       "FROM comments ".
       "LIMIT $offset, $rec_limit";
      

$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
    echo "<strong>Date :{$row['date']}  </strong><br> ".
         "<strong>Name : {$row['name']} </strong><br> ".
         "Comment : {$row['comment']} <br> ".
         "<br><br>";
}

if( $page > 0 )
{
   $last = $page - 2;
   echo "<a href=\"$_PHP_SELF?page=$last\">Previous Page</a> |";
   echo "<a href=\"$_PHP_SELF?page=$page\">Next Page</a>";
}
else if( $page == 0 )
{
   echo "<a href=\"$_PHP_SELF?page=$page\">Next Page</a>";
}
else if( $left_rec < $rec_limit )
{
   $last = $page - 2;
   echo "<a href=\"$_PHP_SELF?page=$last\">Previous Page</a>";
}
mysql_close($conn);
?>


This all works fine, apart from I want it do display 5 results per page, can someone please tell me what I need to change, how and where?
Many thanks
Matt

no avatar
tutorialspoint
Site Admin
 
Posts: 144
Joined: Fri Apr 27, 2007 6:52 pm

Re: PHP Code

by tutorialspoint » Tue May 28, 2013 9:28 am

Hope you got the answer.

no avatar
adlena
 
Posts: 1
Joined: Thu Jul 04, 2013 6:30 am

Re: PHP Code

by adlena » Thu Jul 04, 2013 7:07 am

thanks for sharing, i just have completed my course in PHP
adlena

Return to General Discussion

cron