Location: PHPKode > scripts > Show any MySQL table > show-any-mysql-table/read_tables.php
<?php
/*created by Anderson Manuel
  hide@address.com
  the script below read is to read a table from any mysql database  and
  generate a xml doc, where a javascript can read the data and put it in a 
  html table.
*/
class read_tables
{

 var $host  ;
 var $user  ;
 var $pass  ;
 var $database ;
 var $table ;
  	
  
  function read_tables($host,$user,$pass,$database,$table)
  {
  	$this->host=$host;
  	$this->user=$user;
  	$this->pass=$pass;
  	$this->database=$database;
  	$this->table=$table;
    $this->genXml();
  	
  }
  
   	function openCon()
   	{
   		$connect = mysql_connect($this->host, $this->user,$this->pass);
 	 if(!$connect) 
 	 {  die('Not connected : ' . mysql_error());
 	 }
 	 $db_select = mysql_select_db($this->database,$connect);
 	 if(!$db_select)
 	 {die('Cant use db :'. mysql_error());}		 
 	return $connect;
   	}
   	
  	 function closeCon($connect)
     {
 	     mysql_close($connect);
     }

 function retrieve_result()
 {
 	$this->openCon();
 
 	 $result = mysql_query("SELECT * FROM ".$this->table." where 1");
  
 	  return $result;
 	
 }
 
function num_fields($result)
 {
 	$fields = mysql_num_fields($result);
 	return $fields;
 }

 function field_name($result,$fields,$i)
 {
 	 $name  = mysql_field_name($result, $i);
   return $name;
 }
 
 
 function genXml()//funtion to generate a xml 
 {
 	
 	 $dom = new DOMDocument("1.0");
   $root = $dom->createElement("data");//first node or 1st tag
   $parnode = $dom->appendChild($root);
   $j=0;
   $result = $this->retrieve_result();
   $fields = $this->num_fields($result);
  
   
    header("Content-type: text/xml");
   $body = $dom->createElement("heads");
   for($i=0; $i<$fields; $i++)
    { 
    	$field_name =  $this->field_name($result,$fields,$i);//read the fields name of the table and fill in xml to be a header of html table
    	$col = $dom->createElement("cols",strtoupper($field_name));
      $body->appendChild($col);	
    }	
    $root->appendChild($body);//end here
    
    //raed the datas and fill the body of xml,
    while ($row = mysql_fetch_array($result))
		{ 
		  $reg = $dom->createElement("regs");//node of registers
		  for($i=0; $i<$fields; $i++)
		  {
		  $name = $dom->createElement("item",$row[$i]);//child of node registers
	  	
		  $reg ->appendChild($name);
		  $root->appendChild($reg);
		  $dom->appendChild($root);
		  }
		}
      
      
      mysql_free_result($result);
	    $this->closeCon();
   echo $dom->saveXML();
 }
 
}
?>
Return current item: Show any MySQL table