Posted By

r3morse on 11/12/09


Tagged

mysql class php mysqli oo


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

jlan
weblogics
ekarakas
sbcjr
Alex42195


Simple MySQLi Database Class


 / Published in: PHP
 

A very simple class that quickly gets you interacting with a database, as long as you know sql :P.

  1. /**
  2.  * Database connection class.
  3.  * $db = new db(array(host, user, password, database));
  4.  * $db->connect();
  5.  * $clean = $db->clean($dirty);
  6.  * $db->query("");
  7.  * $db->disconnect();
  8.  */
  9. class db {
  10.  
  11. private $db = array();
  12. private $connection;
  13.  
  14. public function db($args = array()) {
  15. $this->db['server'] = $args['server'];
  16. $this->db['username'] = $args['username'];
  17. $this->db['password'] = $args['password'];
  18. $this->db['database'] = $args['database']; }
  19.  
  20. public function connect() {
  21. $this->connection = mysqli_connect($this->db["server"], $this->db["username"], $this->db["password"]);
  22. $this->select_db(); }
  23.  
  24. public function disconnect() {
  25. mysqli_close($this->connection);
  26. $this->connection = null; }
  27.  
  28. public function select_db() {
  29. mysqli_select_db($this->connection, $this->db["database"]); }
  30.  
  31. public function query($sql) {
  32. $this->result = mysqli_query($this->connection, $sql); }
  33.  
  34. public function is_connected() {
  35. return ($this->connection) ? true : false; }
  36.  
  37. public function clean($dirty) {
  38. if (!is_array($dirty)) {
  39. $dirty = ereg_replace("[\'\")(;|`,<>]", "", $dirty);
  40. $dirty = mysqli_real_escape_string($this->connection, trim($dirty));
  41. $clean = stripslashes($dirty);
  42. return $clean; };
  43. $clean = array();
  44. foreach ($dirty as $p=>$data) {
  45. $data = ereg_replace("[\'\")(;|`,<>]", "", $data);
  46. $data = mysqli_real_escape_string($this->connection, trim($data));
  47. $data = stripslashes($data);
  48. $clean[$p] = $data; };
  49. return $clean; }
  50.  
  51. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: r3morse on November 12, 2009

Thanks largely to: http://snipplr.com/view/12697/simple-database-class/

You need to login to post a comment.