0

I have a php class that deals with MySql data given below

<?php

class DB_Functions
{

    function __construct()
    {   
        require_once 'DB_Connect.php';
        $db=new DB_Connect();
        $db->connect();
    }
    function __destruct()
    {

    }
    public function getDetails($username,$password)
    {
        $result = mysql_query("Select * from teachertb where Username = '$username' and password = '$password'") or die(mysql_error());
        $no_of_rows = mysql_num_rows($result);
        if($no_of_rows>0)
        {
            return $result;
        }       
        else
        {
            return false;
        }
    }
    public function getClass($res)
    {
        while($r=mysql_fetch_array($res))
        {   
            echo $r[0]."<br>";
            echo $r[1]."<br>";
            echo $r[2]."<br>";
            echo $r[3]."<br>";
        }
    }
}
$d=new DB_Functions();
$res=$d->getDetails("abcd","abcd");
$d->getClass($res);
while($r=mysql_fetch_array($res))
{   
    echo $r[0]."<br>";
    echo $r[1]."<br>";
    echo $r[2]."<br>";
    echo $r[3]."<br>";
}
?>

In this code actually i want to use the resultset to display the data from the table and use the same resultset in the other function to do some other functionality using the data. But i've noticed that the same resultset cannot be used more than one times. Why is it so? And how can i use the same resultset multiple times.

1
  • You might want to consider using the mysqli extension instead of the mysql extension, as the mysql extension is depricated since PHP 5.5.x. Commented Oct 20, 2015 at 19:06

1 Answer 1

1

The reason for this is that everytime you call mysql_fetch_array the next row of the result set is used.

There are two options:

First

You have to call getClass with the return value of $r=mysql_fetch_array($res) which would be $r in your case (for every returned row). Or you have to first put all rows in an array and pass that to other functions.

while($r=mysql_fetch_array($res))
{
    // call another function with $r as parameter
}

or

$result = array();
while($r=mysql_fetch_array($res))
{
     $result[] = $r;
}
// $result array now contains all rows and can be passed to other methods.

See http://php.net/manual/de/function.mysql-fetch-array.php

Second

You could also reset to internal pointer of the resource by calling mysql_data_seek (see http://php.net/manual/de/function.mysql-data-seek.php), then you could use mysql_fetch_array again starting from the first row.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.