I have written this class because I find that the MySQL commands that are provided in PHP are not obect orientated and are quite lengthy to have to retype time and time again.

 

Old Way

  1. mysql_connect('localhost', 'username', 'password');
  2. mysql_select_db('database') or die('<p>Could not select database</p>');
  3. $sqlQueryString = 'SELECT *
  4. FROM MyTable
  5. WHERE ID = 200';
  6. $sqlQuery = mysql_fetch_array($sqlQueryString);
  7. while ($data = mysql_fetch_array($sqlQuery)) {
  8. // Do something with your data
  9. echo $data['value'];
  10. }

New Way

  1. $datas = new MySQL();
  2. $datas->query('SELECT *
  3. FROM MyTable
  4. WHERE ID = 200');
  5. while ($data = $datas->result()) {
  6. // Do something with your data
  7. echo $data['value'];
  8. }

The Class

Download the class mysql.inc.php

  1. class MySQL{
  2. private $connection;
  3. private $db;
  4. private $query;
  5.  
  6. function __construct() {
  7. $this->connection = mysql_connect('localhost', 'username', 'password');
  8. $this->db = mysql_select_db('database');
  9. }
  10.  
  11. function __destruct() {
  12. mysql_close($this->connection);
  13. }
  14.  
  15. function query($query) {
  16. $this->query = mysql_query($query, $this->connection) or die('<p>'.mysql_error($this->connection).'<br>'.$query.'</p>');
  17. }
  18.  
  19. function count() {
  20. return mysql_num_rows($this->query);
  21. }
  22.  
  23. function result() {
  24. return mysql_fetch_array($this->query, MYSQL_ASSOC);
  25. }
  26.  
  27. function result_array() {
  28. while ($row = mysql_fetch_array($this->query, MYSQL_ASSOC)) {
  29. $data[] = $row;
  30. }
  31. return $data;
  32. }
  33.  
  34. function insert_id() {
  35. return mysql_insert_id($this->connection);
  36. }
  37. }

Comments:

Leave a Reply



(Your email will not be publicly displayed.)


Captcha Code

Click the image to see another captcha.