Posted By

claudiowebdesign on 10/05/11


Tagged

database sql php oop


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

Shoobis
dubogii
tux-world
gecube


Database php class


 / Published in: PHP
 

URL: http://claudiobonifazi.com

That's something quick. A basic php class to manage properly a database. Thanks to magic methods opening a database is almost automatic.

  1. <?php
  2.  
  3. class Database{
  4. private $host = '127.0.0.1';
  5. private $dbname = 'example';
  6. private $dbpwd = '';
  7. private $dbuser = 'root';
  8. public $link;
  9.  
  10. function __construct(){
  11. $this->link = mysql_connect($this->host,$this->dbuser,$this->dbpwd) or die(mysql_error());
  12. mysql_select_db($this->dbname,$this->link) or die(mysql_error());
  13. }
  14. function __destruct(){
  15. mysql_close($this->link);
  16. }
  17.  
  18. public static function filter($data){
  19. if(is_array($data))
  20. $data = array_map('Database::filter', $data);
  21. else{
  22. $data = trim(htmlentities(strip_tags($data)));
  23. $data = stripslashes($data);
  24. $data = mysql_real_escape_string($data);
  25. }
  26. return $data;
  27. }
  28.  
  29. // $table = string, $conditions = array, $limit = number
  30. public static function readRecord( $table, $conditions, $limit=false ){
  31. $query = "SELECT * FROM $table WHERE ";
  32. foreach($conditions as $a => $b)
  33. $query .= "$a = '".Database::filter($b)."' AND ";
  34. $query = substr($query,0,-4).($limit ? ' LIMIT '.Database::filter($limit):'');
  35. return mysql_fetch_array( mysql_query($query),MYSQL_ASSOC);
  36. }
  37.  
  38. // $table = string, $values = array
  39. public static function addRecord( $table, $values ){
  40. $q_1 = "INSERT INTO $table(";
  41. $q_2 = ") VALUES(";
  42. foreach($values as $field => $val){
  43. $q_1 .= $field.', ';
  44. $q_2 .= "'".Database::filter($val)."', ";
  45. }
  46. return mysql_query(substr($q_1,0,-2).substr($q_2,0,-2).')');
  47. }
  48.  
  49. // $table = string, $conditions = array, $limit = number
  50. public static function removeRecord( $table, $conditions, $limit=false ){
  51. $query = "DELETE FROM $table WHERE ";
  52. foreach($conditions as $a => $b)
  53. $query .= "$a = '".Database::filter($b)."' AND ";
  54. $query = substr($query,0,-4).($limit ? ' LIMIT '.Database::filter($limit):'');
  55. return mysql_fetch_array( mysql_query($query),MYSQL_ASSOC);
  56. }
  57. }
  58.  
  59. ?>

Report this snippet  

You need to login to post a comment.