coop Posted August 27, 2007 Share Posted August 27, 2007 Hi all, I'm new to php but come from using Actionscript, so I understand alot of what PHP has to offer. I'm learning php so I can use it with Flash - I'm using a friends of Ed book which is good but some things are unexplained. This class is from the book and is used to connect to the database - I understand the idea of classes and how they work but could someone give a quick explanation of how this class is supposed to work, and do you think it is better to use a class for this or use seperate statments, (which I feel more comfortable using, ,cos I can understand them better. ) such as $con = mysql_connect('localhost','root','root'); <?php class Database { protected $host; protected $user; protected $pwd; protected $dbName; protected $flash; protected $dbLink; protected $result; protected $resultObj; function __construct($host, $user, $pwd, $dbName, $flash=1){ $this->host = $host; $this->user = $user; $this->pwd = $pwd; $this->dbName = $dbName; $this->flash = $flash; $this->connect(); } public function connect() { try { $this->dbLink = @mysqli_connect($this->host, $this->user, $this->pwd, $this->dbName); if (!$this->dbLink) { throw new Exception ("Couldn't connect $this->user to $this->dbName"); } } catch (Exception $e) { echo $this->flash ? 'error='.urlencode($e->getMessage()) : $e->getMessage(); exit(); } return $this->dbLink; } public function query($query) { try { $this->result = mysqli_query($this->dbLink, $query); if (!$this->result) { throw new Exception ('MySQL Error: ' . mysqli_error($this->dbLink)); } } catch (Exception $e) { echo $this->flash ? 'error='.urlencode($e->getMessage()) : $e->getMessage(); exit(); } $this->resultObj = new MyResult($this->result); return $this->resultObj; } public function close(){ mysqli_close($this->dbLink); } } class MyResult { protected $theResult; public $num_rows; function __construct($r) { if (is_bool($r)) { $this->num_rows = 0; } else { $this->theResult = $r; $this->num_rows = mysqli_num_rows($r); } } function fetch_assoc() { $newRow = mysqli_fetch_assoc($this->theResult); return $newRow; } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/66870-class-explanation/ Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.