MySQL Database Access

Page 1 of 1

0 Replies - 339 Views - Last Post: 19 October 2006 - 05:35 PM

#1 rockstar_  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 34
  • View blog
  • Posts: 189
  • Joined: 16-October 06

MySQL Database Access

Posted 19 October 2006 - 05:35 PM

Description: Instantiate this class, easily run queries, automatic deconstruction at the end of the script.
I've included PHPdoc style commenting as well.A Database class to wrap all the mysql functions in php
<?php

class Database {

  var $dbh;

  function Database( $_host, $_user, $_pass, $_dbname ) {

    $this->host = $_host;
    $this->user = $_user;
    $this->pass = $_pass;
    $this->dbname = $_dbname;

    $this->dbh = mysql_connect( $this->host, $this->user, $this->pass );
    $error = mysql_errno( $this->dbh );

    if ( $error ) {
      error( E_ERROR, 'ERROR : Cannot Connect to Database ''. $this->dbname .''' );
      exit;
    }

    mysql_select_db( $this->dbname, $this->dbh );
    $error = mysql_errno( $this->dbh );     

    if ( $error ) {
      error( E_ERROR, 'ERROR : Cannot Select Database ''. $this->dbname .''' );
      exit;
    }

    register_shutdown_function( array( &$this, '_close' ) );

  }

  function _close() {
    mysql_close( $this );
  }

  /**
    * Wraps the mysql_query function for the abstracted Database class
    * @param $_qry The query to execute
    * @return The result of the query
    */
  function query( $_qry ) {

    $result = mysql_query( $_qry, $this->dbh );
    $error = mysql_errno( $this->dbh );

    if ( $error ) {
      error( E_ERROR, 'ERROR : Cannot Perform Query ''. $_qry .''' );
      exit;
    }

    return $result;

  }

}

/* Usage of the class */
$database = new Database( 'database_host', 'database_user', 'database_password', 'database_name' );
$result = $database->query( "SELECT * FROM table WHERE field='value';" );
echo $result

?>



Is This A Good Question/Topic? 0
  • +

Page 1 of 1