DataObject class


/ Published in: PHP
Save to your folder(s)

Abstract class from which other classes can be derived to handle database access and data retrieval.
Constants for database connection (DB_DSN, DB_USERNAME, etc.) must be set in another php file (eg. config.php)


Copy this code and paste it in your HTML
  1. abstract class DataObject
  2. {
  3. protected $data = array();
  4.  
  5. public function __construct( $data )
  6. {
  7. foreach ( $data as $key => $value ) {
  8. if ( array_key_exists( $key, $this->data ) )
  9. $this->data[$key] = $value;
  10. }
  11. }
  12.  
  13. public function getValue( $field )
  14. {
  15. if ( array_key_exists( $field, $this->data ) )
  16. return $this->data[$field];
  17. else
  18. exit( "Field not found" );
  19. }
  20.  
  21. public function getValueEncoded( $field )
  22. {
  23. return htmlspecialchars( $this->getValue( $field ) );
  24. }
  25.  
  26. protected function connect()
  27. {
  28. try {
  29. $conn = new PDO( DB_DSN, DB_USERNAME, DB_PWD );
  30. $conn->setAttribute( PDO::ATTR_PERSISTENT, TRUE );
  31. $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  32. }
  33. catch ( PDOException $e) {
  34. exit( 'Connection failed: '. $e->getMessage() );
  35. }
  36.  
  37. return $conn;
  38. }
  39.  
  40. protected function disconnect( $conn )
  41. {
  42. $conn = NULL;
  43. }
  44. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.