This is a database connection class and file name MySQLResultSet.php
<?php
class MySQLResultSet implements Iterator{
private $strSQL;
private $databasename;
private $connection;
private $result;
function __construct($strSQL, $databasename, $connection){
if(isset($connection)){
mysql_select_db($databasename,$connection);
$this->result=mysql_query($strSQL);
}
}
function current (){
return $this->currentrow;
}
function key (){
return $this->key;
}
function valid (){
return $this->valid;
}
function next(){
if($this->currentrow = mysql_fetch_array($this->result)){
$this->valid = true;
$this->key++;
}else{
$this->valid = false;
}
}
function rewind (){
if(mysql_num_rows($this->result) > 0){
if(mysql_data_seek($this->result, 0)){
$this->valid = true;
$this->key = 0;
$this->currentrow = mysql_fetch_array($this->result);
}
}else{
$this->valid = false;
}
}
function getRow(){
$this->next();
return $this->current();
}
function numRows(){
return $this->rows=mysql_num_rows($this->result);
}
}
class MySQLConnect extends MySQLResultSet{
//data members
private $connection;
private static $instances = 0;
//methods
function __construct($hostname, $username, $password){
if(MySQLConnect::$instances == 0){
$this->connection = mysql_connect($hostname,$username,$password) or
die ( mysql_error(). " Error no:".mysql_errno());
MySQLConnect::$instances = 1;
}else{
$msg = "Close the existing instance of the ".
"MySQLConnect class.";
die($msg);
}
}
function createResultSet($strSQL, $databasename){
$rs = new MySQLResultSet($strSQL, $databasename, $this->connection );
return $rs;
}
function close(){
MySQLConnect::$instances = 0;
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
}
?>
This class used in a file which name is getresult.php
$con = new MySQLConnect('localhost', 'root', '');
$strsql="SELECT name FROM student";
//get result set
$rs = $con->createResultSet($strsql, 'innoDB');
echo "<div style=\"text-align:center\">";
while($row = $rs->getRow()){
echo $row['name'];
echo "<br />\n";
}
echo "<br />";
echo "</div>\n";
