mysql class

By sean on Mar 04, 2010

simple mysql class.
usage: change predefined vars under 'mysql server configuration' to suit your environment.

example.php -

<?php
include 'mysql.class.php';
$mysql = new mysql_db();

//result will always be in array format
$result = $mysql->fetch_array('SELECT * FROM `table`');

printf('<pre>%s</pre>', print_r($result, 1));

$mysql->query('UPDATE `table` SET `id` = 23 WHERE `id` = 22');
?>
<?php
/**
 *  @author Sean Wragg <seanwragg@gmail.com>
 *  @version 1.0 bRC3 mysql.class.php
 */

class mysql_db {
    // mysql server configuration
    private $dbhost = 'localhost';
    private $dbuser = 'username'; 
    private $dbpass = 'password'; 
    private $dbname = 'database';
    protected $mysql;

    // check if connection is alive, if not establish it
    function __construct() {
        if ( !is_resource($this->mysql) ) {
            $this->mysql = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpass );
            mysql_select_db( $this->dbname, $this->mysql ) or $this->error();
        }
    }

    // error reporting
    private function error() {
        return printf( '<b>MySQL ERROR:</b> %s (%d)', mysql_error(), mysql_errno() );
   }

    // handles queries resulting in output
    public function fetch_array( $query ) {
        $mysql_query = mysql_query( $query, $this->mysql );
        while( $result = mysql_fetch_array( $mysql_query, MYSQL_ASSOC ) ) {
            $return[] = $result;
        }
        return $return;
    }

    // handles statements: update, insert etc. 
    public function query( $query ) {
        return mysql_query( $query, $this->mysql );
    }
}

?>

Comments

Sign in to comment.
Bobbtyisdead   -  Jun 18, 2010

Is this just intended as a replacement for mysqli for servers without php5 installed?

 Respond  
F*U*R*B*Y*   -  Jun 18, 2010

..... im not that silly, i have that installed......

fixed..... nvm XD

 Respond  
sean   -  Jun 18, 2010

You need the mysql extension installed for php to recognize mysql functions <33

 Respond  
F*U*R*B*Y*   -  Jun 18, 2010

i get errors, after a bit of debugging, its saying that mysql_connect isn't a function...

ideas? :P

 Respond  
sean   -  Mar 11, 2010

thanks for the comments :D

 Respond  
F*U*R*B*Y*   -  Mar 04, 2010

nice mate :)

 Respond  
Hawkee   -  Mar 04, 2010

Great, it's definitely helpful to have one of these. I like how you combined mysql_query and mysql_fetch_array into a single function.

 Respond  
Korvin   -  Mar 04, 2010

nice set of tools, 8/10 +1 like

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.