Ash
Ash

Reputation: 61

mysql_fetch_array not fetching complete data?

I have a code which fetches data from a mysql table and converts it into pdf document, the code is working fine except it is skipping row 1.

Here is the code from which i have removed the pdf generation process since the problem is in the loop which is fetching data.

Please help.

<?php
    session_start();
if(isset($_SESSION['user']))
{
    $cr = $_POST['cour'];
    $s = $_POST['sem'];
    require('fpdf.php');
    include('../includes/connection.php');
    $sql = "SELECT * FROM `student` WHERE AppliedCourse ='$cr'";
    $rs = mysql_query($sql) or die($sql. "<br/>".mysql_error());
    if(!mysql_fetch_array($rs))
    {
        $_SESSION['db_error'] = "<h2><font color = 'RED'>No such course found! Pease select again.</font></h2>";
        header('Location: prinrepo.php');
    }
    else {

    for($i = 0;$i <= $row = mysql_fetch_array($rs);$i++)
     {
            $formno[$i] = $row ['FormNo']; 
            $rno[$i] = $row ['rollno'];
            $snm[$i] = $row ['StudentNm'];          
            $fnm[$i] = $row ['FathersNm'];
            $mnm[$i] = $row ['MothersNm'];
            $addr[$i] = $row['Address'];
            $pic[$i] = $row['imagenm'];
            $comm[$i] = $row['SocialCat'];

        echo $formno[$i]."<br />";
        echo $rno[$i]."<br />";
        echo $snm[$i]."<br />";
        echo $fnm[$i]."<br />";
        echo $mnm[$i]."<br />";
        echo $addr[$i]."<br />";
        echo $pic[$i]."<br />";
        echo $comm[$i]."<br />";
        echo "<br />";
    }
    }
    mysql_close($con);
    }
?>

Upvotes: 0

Views: 269

Answers (1)

koopajah
koopajah

Reputation: 25552

You are fetching the first row outside of your for() loop then you miss it.

After mysql_query() your should use mysql_num_rows() to check if there are any rows in your result and then fetch them in the for loop.

More info here : http://php.net/manual/fr/function.mysql-num-rows.php

Your code would look like this :

$sql = "SELECT * FROM `student` WHERE AppliedCourse ='$cr'";
$rs = mysql_query($sql) or die($sql. "<br/>".mysql_error());
if(0 == mysql_num_rows($rs)) {
    $_SESSION['db_error'] = "<h2><font color = 'RED'>No such course found! Pease select again.</font></h2>";
    header('Location: prinrepo.php');
} else {
    for($i = 0;$i <= $row = mysql_fetch_array($rs);$i++)
     {
        // Your code
    }
}

Upvotes: 2

Related Questions