Stephen Groom Taking a shot at becoming a Poker Pro

3Jun/080

Simple MySQL class

While having a trawl around my local sites folder looking for something of use to the world wide web I remembered my MySQL class that has gone unedited for a long time but has been used by every site I have made since I upgraded to PHP5.

It contains very little in the way of functionality but I use it to save the trouble of typing out mysql functions for each operation. It is called using

[php]$mysql=new mysql('HOST', USERNAME', 'PASSWORD', 'DATABASE');
[/php]

It also contains the following functions

[php] $mysql->Close(); //close connection
$mysql->Free($RESULT_SET) //call to mysql_free_result();
$mysql->Query($query); //Query with basic error handling
$mysql->FetchArray($RESULT_SET); //Fetch array from a result set
$mysql->NumRows($RESULT_SET); //Get number of rows in a result set
$mysql->QueryArray($query) //Used to query AND return the result as an array
?>[/php]

[b]Here is the class as it stands:[/b]

[php]
class mysql {
var $server;
var $user;
var $passwd;
var $dbname;
var $link; //MySQL link identifier
var $rs; //Result set
var $q; //Number of queries

function mysql ($server = 'localhost', $user = 'root', $pass = '', $dbname = '') {
$this->server = $server;
$this->user = $user;
$this->passwd = $pass;
$this->dbname = $dbname;

$this->connect ();
}

function Connect () {
$this->link = mysql_connect ($this->server, $this->user, $this->passwd);
mysql_select_db ($this->dbname, $this->link);
}
function Close () {
return (mysql_close($this->link));
}
function Free($rs = '')
{
if (is_resource($rs))
mysql_free_result($rs);
}
function Query($query) {
$this->rs = mysql_query ($query, $this->link);
if (!$this->rs)
{
echo('Error: Invalid query "'.$query.'"...<br/>');
echo('Error: '.mysql_errno().'<br/>');
echo('Error: '.mysql_error().'<br/>');
} else {
$this->q++;
return ($this->rs);
}
}

function FetchArray($rs = '') {
if ($rs == '')
$rs = $this->rs;

return (mysql_fetch_assoc ($rs));
}

function NumRows($rs = '') {
if ($rs == '')
$rs = $this->rs;
return (mysql_num_rows($rs));
}
function QueryArray($rs = ''){
if($rs =='')
return 0;
$rs=$this->Query($rs);
$this->q++;
$array=$this->FetchArray($rs);
$this->Free($rs);
return $array;
}
}
?>
[/php]
and here is a link to the [url=/sources/mysql.class.php]current source[/url] which I use on this website.

Love
Stephen :)

Share
Filed under: PHP Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.