Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // ANSWER #1
- class datareader {
- var $string;
- var $type;
- var $query;
- var $result;
- function read($string,$query = "") {
- $this->string = $string;
- if (!empty($query)) $this->query = $query;
- $find_type = "/([A-Za-z]+):\/\//";
- preg_match($find_type,$string,$type);
- $this->type = $type[1];
- if ($this->store())
- return true;
- else
- return false;
- }
- protected function store() {
- switch($this->type) {
- case "db":
- $find_type = "/db:\/\/([A-Za-z.0-9]+):([A-Za-z0-9_]+):([A-Za-z0-9]+):([A-Za-z0-9]+):([A-Za-z_0-9]+)/";
- preg_match($find_type,$this->string,$match);
- if (mysql_connect($match[1],$match[3],$match[4]))
- mysql_select_db($match[2]);
- else
- die(mysql_error());
- if (!empty($this->query))
- $sql = $this->query;
- else
- die("No query input");
- $get = mysql_query($this->query);
- if ($this->result = mysql_fetch_array($get))
- return true;
- else
- return false;
- break;
- case "file":
- $find_type = "/file:\/\//";
- $replace = preg_replace($find_type,"",$this->string);
- if (file_exists($replace))
- $this->result = file($replace);
- else
- die("File ".$replace." not found!");
- }
- }
- function formatRS() {
- switch($this->type) {
- case "db":
- $return = "<table border=\"1\"><thead><th>#</th><td>Table Name</td></thead>";
- $c = 0;
- foreach ($this->result as $row) {
- $return .= "<tr><td>".$c."</td><td>".$row."</td>";
- $c++;
- }
- $return .= "</table>";
- break;
- case "file":
- $return = "<table border=\"1\">";
- foreach ($this->result as $row) {
- $tr = explode(",",$row);
- $return .= "<tr>";
- foreach ($tr as $td) {
- $return .= "<td>".$td."</td>";
- }
- $return .= "</tr>";
- }
- $return .= "</table>";
- break;
- }
- return $return;
- }
- }
- ?>
- Write a class to read from a database (MySql) table or a flat file and
- return the results formatted in a HTML table.
- The class should work when called using the following code:
- <?php
- $SQL='SHOW TABLES';
- require_once('datareader.class.php');
- $datareader=new datareader();
- $datareader->read('db://localhost:jobtstdb:root::jobtst',$SQL);
- //arguments "db://HOST:DBNAME:USER:PASS:TBL",query
- echo $datareader->formatRS();
- $datareader->read('file://C:\phpdev\www\csv\test.csv:,');
- //arguments "file://FILEPATH:DELIMITER"
- echo $datareader->formatRS();
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement