Error displaying records from MySQL database

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Gary Baardman
    New Member
    • Aug 2010
    • 3

    Error displaying records from MySQL database

    I am having a few problems returning records from a mySQL database using PHP.

    Firstly I must say I am trying to create a video album using MySQL, PHP and using pagination.

    My first problem is if I want to retrieve the first 3 records, only the first record is retrieved and then the next two records are duplicates of the first record.

    My second problem is if I want to retrieve all of the records (there are currently 3), only the total-1 records are returned - I can not retrieve the last record.

    Below is my PHP code for the script:

    Code:
    <?php
    
    //Connect to the database
    $user="USERNAME"; 
    $password="PASSWORD";
    $database="DATABASE";
    $con = mysql_connect("localhost",$user,$password) or die ('Could not connect: ' . mysql_error());
    
    
    
    mysql_select_db($database, $con) or die( "Unable to select database");
    // find out how many rows are in the table 
    $sql = "SELECT * FROM vids";
    $result = mysql_query($sql, $con);
    $r = mysql_fetch_row($result);
    $numrows = $r[0];
    
    // number of rows to show per page
    $rowsperpage = 1;
    
    // find out total pages
    $totalpages = ceil($numrows / $rowsperpage);
    
    // get the current page or set a default
    if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
       // cast var as int
       $currentpage = (int) $_GET['currentpage'];
    } else {
       $currentpage = 1;
    }
    
    // if current page is greater than total pages...
    if ($currentpage > $totalpages) {
       // set current page to last page
       $currentpage = $totalpages;
    } // end if
    // if current page is less than first page...
    if ($currentpage < 1) {
       // set current page to first page
       $currentpage = 1;
    } 
    
    // the offset of the list, based on current page 
    $offset = ($currentpage - 1) * $rowsperpage;
    
    // get the info from the db 
    $sql = "SELECT * FROM vids LIMIT $offset, $rowsperpage";
    $result = mysql_query($sql, $con) or trigger_error("SQL", E_USER_ERROR);
    
    // Assign variables for videos
    $query  = "SELECT *  FROM vids";
    $result = mysql_query($query) or die ('Error: '.mysql_error ());
    $row = mysql_fetch_row($result);
    
    $id = $row[0];
    $url = $row[1];
    $page_url = $row[2];
    $title = $row[3];
    $desc = $row[4];
    $date_add = $row[5];
    $date_rec = $row[6];
    $place = $row[7];
    $altitude = $row[8];
    $jump_no = $row[9];
    
    // while there are rows to be fetched...
    while ($list = mysql_fetch_assoc($result)) {
       // echo data
        $id = $row[0];
    	$url = $row[1];
    	$page_url = $row[2];
    	$title = $row[3];
    	$desc = $row[4];
    	$date_add = $row[5];
    	$date_rec = $row[6];
    	$place = $row[7];
    	$altitude = $row[8];
    	$jump_no = $row[9];
    		 echo "<div class='sky_cont'>
        <div class='sky_vid'><a class='video' href=\"$url\"><img src='http://www.netlinksurveyors.co.uk/test/images/lgo.jpg' alt=\"$title\" Border='0' /></a></div>
    	<p><h4><a href=\"$page_url\" target='_blank'>$title</a></h4>$desc</p>
        </div>";
    
    }
    
    
    
    /******  build the pagination links ******/
    // if not on page 1, don't show back links
    if ($currentpage > 1) {
       // show << link to go back to page 1
       echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
       // get previous page num
       $prevpage = $currentpage - 1;
       // show < link to go back to 1 page
       echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
    } 
    
    // range of num links to show
    $range = 3;
    
    // loop to show links to range of pages around current page
    for ($x = ($currentpage - $range); $x < (($currentpage + $range)  + 1); $x++) {
       // if it's a valid page number...
       if (($x > 0) && ($x <= $totalpages)) {
          // if we're on current page...
          if ($x == $currentpage) {
             // 'highlight' it but don't make a link
             echo " [<b>$x</b>] ";
          // if not current page...
          } else {
             // make it a link
             echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
          }
       } 
    }
    
    // if not on last page, show forward and last page links        
    if ($currentpage != $totalpages) {
       // get next page
       $nextpage = $currentpage + 1;
        // echo forward link for next page 
       echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
       // echo forward link for lastpage
       echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
    } // end if
    /****** end build pagination links ******/
    
    
    ?>
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    it is good style to name all the fields in an SQL query explicitly, because that can save you much memory, esp. when you don’t need all fields. additionally, you can see by looking at the query, what it should contain (doesn’t require knowledge of the DB itself).

    Code:
    // inefficient
    SELECT * FROM table
    // better
    SELECT `field_1`, `field_2`, `field_3` FROM table
    one more point, you can pass the fetch mode in the mysql_fetch_* function, so that PHP doesn’t create more array members than necessary (currently you have a named and numerically indexed array).

    Code:
    // get the info from the db 
    $sql = "SELECT * FROM vids LIMIT $offset, $rowsperpage";
    [B]$result[/B] = mysql_query($sql, $con) or trigger_error("SQL", E_USER_ERROR);
     
    // Assign variables for videos
    $query  = "SELECT *  FROM vids";
    [B]$result[/B] = mysql_query($query) or die ('Error: '.mysql_error ());
    you’re overwriting the first query immediately …

    Code:
    while ([B]$list[/B] = mysql_fetch_assoc($result)) {
        $id = [B]$row[/B][0];
    do you see something obvious?
    Last edited by Dormilich; Aug 20 '10, 06:15 AM.

    Comment

    • Gary Baardman
      New Member
      • Aug 2010
      • 3

      #3
      I can see what the problem is with the overwritting of the variable $results, simply rename the second variable?

      I dont understand what is wrong with the following:
      Code:
      while ($list = mysql_fetch_assoc($result)) {
          $id = $row[0];
      I have modified the script a little, but it still does not display the correct information - only the first record.

      PHP code is below:
      Code:
      <?php
      
      //Connect to the database
      $user="USERNAME"; 
      $password="PASSWORD";
      $database="DATABASE";
      $con = mysql_connect("localhost",$user,$password) or die ('Could not connect: ' . mysql_error());
      
      mysql_select_db($database, $con) or die( "Unable to select database");
      
      // find out how many rows are in the table 
      $sql = "SELECT * FROM vids";
      $result = mysql_query($sql, $con);
      $r = mysql_fetch_row($result);
      $numrows = $r[0];
      
      // number of rows to show per page
      $rowsperpage = 3;
      
      // find out total pages
      $totalpages = ceil($numrows / $rowsperpage);
      
      // get the current page or set a default
      if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
         // cast var as int
         $currentpage = (int) $_GET['currentpage'];
      } else {
         $currentpage = 1;
      }
      
      // if current page is greater than total pages...
      if ($currentpage > $totalpages) {
         // set current page to last page
         $currentpage = $totalpages;
      } // end if
      // if current page is less than first page...
      if ($currentpage < 1) {
         // set current page to first page
         $currentpage = 1;
      } 
      
      // the offset of the list, based on current page 
      $offset = ($currentpage - 1) * $rowsperpage;
      
      
      
      // Assign variables for videos
      /*$query  = "SELECT *  FROM vids";
      $result = mysql_query($query) or die ('Error: '.mysql_error ());
      $row = mysql_fetch_row($result);
      
      $id = $row[0];
      $url = $row[1];
      $page_url = $row[2];
      $title = $row[3];
      $desc = $row[4];
      $date_add = $row[5];
      $date_rec = $row[6];
      $place = $row[7];
      $altitude = $row[8];
      $jump_no = $row[9];*/
      
      // get the info from the db 
      $sql = "SELECT * FROM vids LIMIT $offset, $rowsperpage";
      $result = mysql_query($sql, $con) or trigger_error("SQL", E_USER_ERROR);
      $row = mysql_fetch_row($result);
      
      $id = $row[0];
      $url = $row[1];
      $page_url = $row[2];
      $title = $row[3];
      $desc = $row[4];
      $date_add = $row[5];
      $date_rec = $row[6];
      $place = $row[7];
      $altitude = $row[8];
      $jump_no = $row[9];
      
      
      // while there are rows to be fetched...
      while ($list = mysql_fetch_assoc($result)) {
      	
      	$id = $row[0];
      $url = $row[1];
      $page_url = $row[2];
      $title = $row[3];
      $desc = $row[4];
      $date_add = $row[5];
      $date_rec = $row[6];
      $place = $row[7];
      $altitude = $row[8];
      $jump_no = $row[9];
      
      		 echo "<div class='sky_cont'>
          <div class='sky_vid'><a class='video' href=\"$url\"><img src='http://www.netlinksurveyors.co.uk/test/images/lgo.jpg' alt=\"$title\" Border='0' /></a></div>
      	<p><h4><a href=\"$page_url\" target='_blank'>$title</a></h4>$desc</p>
          </div>";
      
      }
      
      
      
      /******  build the pagination links ******/
      // if not on page 1, don't show back links
      if ($currentpage > 1) {
         // show << link to go back to page 1
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
         // get previous page num
         $prevpage = $currentpage - 1;
         // show < link to go back to 1 page
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
      } 
      
      // range of num links to show
      $range = 3;
      
      // loop to show links to range of pages around current page
      for ($x = ($currentpage - $range); $x < (($currentpage + $range)  + 1); $x++) {
         // if it's a valid page number...
         if (($x > 0) && ($x <= $totalpages)) {
            // if we're on current page...
            if ($x == $currentpage) {
               // 'highlight' it but don't make a link
               echo " [<b>$x</b>] ";
            // if not current page...
            } else {
               // make it a link
               echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
            }
         } 
      }
      
      // if not on last page, show forward and last page links        
      if ($currentpage != $totalpages) {
         // get next page
         $nextpage = $currentpage + 1;
          // echo forward link for next page 
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
         // echo forward link for lastpage
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
      } // end if
      /****** end build pagination links ******/
      
      
      ?>
      Thanks,
      Gary

      Comment

      • JKing
        Recognized Expert Top Contributor
        • Jun 2007
        • 1206

        #4
        The problem is that you create your loop with the variable $list and it loops three times but you are echo'ing the variables stored in $row not $list. The variables in $row were set just above your loop to the first record in the results which would explain why you get the same result duplicated.

        Code:
        // get the info from the db 
        $sql = "SELECT * FROM vids LIMIT $offset, $rowsperpage";
        $result = mysql_query($sql, $con) or trigger_error("SQL", E_USER_ERROR);
        
        // while there are rows to be fetched...
        while ($row = mysql_fetch_assoc($result)) {
         
        $id = $row[0];
        $url = $row[1];
        $page_url = $row[2];
        $title = $row[3];
        $desc = $row[4];
        $date_add = $row[5];
        $date_rec = $row[6];
        $place = $row[7];
        $altitude = $row[8];
        $jump_no = $row[9];
         
                 echo "<div class='sky_cont'>
            <div class='sky_vid'><a class='video' href=\"$url\"><img src='http://www.netlinksurveyors.co.uk/test/images/lgo.jpg' alt=\"$title\" Border='0' /></a></div>
            <p><h4><a href=\"$page_url\" target='_blank'>$title</a></h4>$desc</p>
            </div>";
         
        }
        Try that.

        Comment

        • Gary Baardman
          New Member
          • Aug 2010
          • 3

          #5
          Thanks JKing, your code got me thinking and I managed to tweak it so it works now.

          The full working code is below:
          Code:
          <?php
          
          //Connect to the database
          $user="USER"; 
          $password="PASSWORD";
          $database="DATABASE";
          $con = mysql_connect("localhost",$user,$password) or die ('Could not connect: ' . mysql_error());
          mysql_select_db($database, $con) or die( "Unable to select database");
          
          
          // Determine number of rows in database
          $query = mysql_query("SELECT * FROM vids");
          $numrows=mysql_num_rows($query);
          
          // number of rows to show per page
          $rowsperpage = 2;
          
          // find out total pages
          $totalpages = ceil($numrows / $rowsperpage);
          
          // get the current page or set a default
          if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
             // cast var as int
             $currentpage = (int) $_GET['currentpage'];
          } else {
             $currentpage = 1;
          }
          
          // if current page is greater than total pages...
          if ($currentpage > $totalpages) {
             // set current page to last page
             $currentpage = $totalpages;
          } // end if
          // if current page is less than first page...
          if ($currentpage < 1) {
             // set current page to first page
             $currentpage = 1;
          } 
          
          // the offset of the list, based on current page 
          $offset = ($currentpage - 1) * $rowsperpage;
          
          // get the info from the db 
          $result = mysql_query("SELECT * FROM vids");
          while($row = mysql_fetch_array($result))
            {
          	  
          $id = $row['id'];  
          $url = $row['url'];
          $page_url = $row['page_url'];;
          $title = $row['title'];
          $desc = $row['desc'];
          $date_add = $row['date_add'];
          $date_rec = $row['date_rec'];
          $place = $row['place'];
          $altitude = $row['altitude'];
          $jump_no = $row['jump_no'];
          
          //Display video
          echo "<div class='sky_cont'> 
              <div class='sky_vid'><a class='video' href=\"$url\"><img src='http://www.netlinksurveyors.co.uk/test/images/lgo.jpg' alt=\"$title\" Border='0' /></a></div>
          	<p><h4><a href=\"$page_url\" target='_blank'>$title</a></h4>$desc</p>
              </div>";
          }
          
          
          /******  build the pagination links ******/
          // if not on page 1, don't show back links
          if ($currentpage > 1) {
             // show << link to go back to page 1
             echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
             // get previous page num
             $prevpage = $currentpage - 1;
             // show < link to go back to 1 page
             echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
          } 
          
          // range of num links to show
          $range = 3;
          
          // loop to show links to range of pages around current page
          for ($x = ($currentpage - $range); $x < (($currentpage + $range)  + 1); $x++) {
             // if it's a valid page number...
             if (($x > 0) && ($x <= $totalpages)) {
                // if we're on current page...
                if ($x == $currentpage) {
                   // 'highlight' it but don't make a link
                   echo " [<b>$x</b>] ";
                // if not current page...
                } else {
                   // make it a link
                   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
                }
             } 
          }
          
          // if not on last page, show forward and last page links        
          if ($currentpage != $totalpages) {
             // get next page
             $nextpage = $currentpage + 1;
              // echo forward link for next page 
             echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
             // echo forward link for lastpage
             echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
          } // end if
          /****** end build pagination links ******/
          
          
          ?>
          The pagination works, but does not limit the number of records shown. I have set the number of rows (records) to be shown per page as 2. I have 4 records in my database and the pagination should show 2 records per page, with a total of two pages. The problem is, it displays all 4 records on pages 1 and two.

          How can I restrict the number of records shown on each page? I thought my code would have done that, but as it seems, it shows all records on the calculated number of pages.

          Thanks for your help :)

          Comment

          Working...