While this may sound obvious, to build a persistent class that will save its properties to a MySQL database table, it's first necessary to create an interface that permits it to access that table in a straightforward way. In this case, the element that will play that role will be a basic MySQL abstraction class whose definition will look as follows: class MySQL { private $result = NULL; private $link = NULL;
// connect to MySQL public function __construct($host, $user, $password, $database) { if (FALSE === ($this->link = mysqli_connect($host, $user, $password, $database))) { throw new Exception('Error : ' . mysqli_connect_error()); } }
// perform query public function query($query) { if (is_string($query) AND !empty($query)) { if (FALSE === ($this->result = mysqli_query($this->link, $query))) { throw new Exception('Error performing query ' . $query . ' Error message :' .mysqli_error($this->link)); } } }
// fetch row from result set public function fetch() { if (FALSE === ($row = mysqli_fetch_assoc($this->result))) { mysqli_free_result($this->result); return FALSE; } return $row; }
// get insertion ID public function getInsertID() { return mysqli_insert_id($this->link); } // count rows in result set public function countRows() { if ($this->result !== NULL) { return mysqli_num_rows($this->result); } } // implement destructor to close the database connection function __destruct() { mysqli_close($this->link); } } The above “MySQL class” does a decent job when it comes to performing queries, counting rows in result sets and finding insertion IDs. Though it isn't suitable for production environments, this sample class encapsulates enough functionality to perfectly fit the needs of a persistent class that will store its properties in a database table. Thus, having at our disposal a class that allows you to abstract access to MySQL tables in a pretty respectable way, the only thing that remains undone is building the class that will persist through several HTTP requests. But guess what? This class will be defined in the last section of this article. Therefore, please read the new few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|