Posted By

tylerhall on 11/30/-1


Tagged

mysql wrapper object db


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

jonbaer
bitcrumb
dantreacy


DBObject Class


 / Published in: Perl
 

  1. /* WORKS IN PHP5 ONLY */
  2.  
  3. class DBObject
  4. {
  5. private $id;
  6. private $id_field;
  7. private $table_name;
  8. private $fields = array();
  9.  
  10. function __construct($table_name, $id_field, $fields)
  11. {
  12. $this->table_name = $table_name;
  13. $this->id_field = $id_field;
  14.  
  15. foreach($fields as $key)
  16. $this->fields[$key] = null;
  17. }
  18.  
  19. function __get($key)
  20. {
  21. return $this->fields[$key];
  22. }
  23.  
  24. function __set($key, $value)
  25. {
  26. if(array_key_exists($key, $this->fields))
  27. {
  28. $this->fields[$key] = $value;
  29. return true;
  30. }
  31. return false;
  32. }
  33.  
  34. function select($id)
  35. {
  36. global $db;
  37.  
  38. $db->query("SELECT * FROM " . $this->table_name . " WHERE " . $this->id_field . " = '$id'");
  39. if(mysql_num_rows($db->result) == 0)
  40. return false;
  41. else
  42. {
  43. $this->id = $id;
  44. $row = mysql_fetch_array($db->result, MYSQL_ASSOC);
  45. foreach($row as $key => $val)
  46. $this->fields[$key] = $val;
  47. }
  48. }
  49.  
  50. function insert()
  51. {
  52. global $db;
  53.  
  54. unset($this->fields[$this->id_field]);
  55. $fields = join(", ", array_keys($this->fields));
  56. $values = "'" . join("', '", $this->fields) . "'";
  57.  
  58. $db->query("INSERT INTO " . $this->table_name . " ($fields) VALUES ($values)");
  59.  
  60. $this->id = mysql_insert_id($db->db);
  61. return $this->id;
  62. }
  63.  
  64. function update()
  65. {
  66. global $db;
  67.  
  68. unset($this->fields[$this->id_field]);
  69. $arrStuff = array();
  70. foreach($this->fields as $key => $val)
  71. $arrStuff[] = "$key = '$val'";
  72. $stuff = implode(", ", $arrStuff);
  73.  
  74. $db->query("UPDATE " . $this->table_name . " SET $stuff WHERE " . $this->id_field . " = '" . $this->id . "'");
  75. return mysql_affected_rows($db->db); // Not always correct due to mysql update bug/feature
  76. }
  77.  
  78. function delete()
  79. {
  80. global $db;
  81. $db->query("DELETE FROM " . $this->table_name . " WHERE " . $this->id_field . " = '" . $this->id . "'");
  82. return mysql_affected_rows($db->db);
  83. }
  84.  
  85. function empty_table()
  86. {
  87. global $db;
  88. $db->query("DELETE FROM " . $this->table_name);
  89. }
  90. }
  91.  
  92. //
  93. // class Person extends DBObject
  94. // {
  95. // function __construct()
  96. // {
  97. // parent::__construct('person', 'person_id', array('name', 'eye_color', 'hair_color'));
  98. // }
  99. // }
  100. //

Report this snippet  

You need to login to post a comment.