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.
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.