MySQL Class

Written something you are proud of, post it here.
Post Reply
User avatar
DomC
Posts: 91
Joined: Mon Jul 18, 2011 1:58 pm

MySQL Class

Post by DomC »

This is a simple class for interacting with a MySQL database.

Your connection details can either be stored as constants (default) or as strings in the class itself.
Each method has info about what it does and any arguments passed to it, however if you would like more info, ask and I will try and help.

[syntax=php]
<?php
class MySQL {

private $dbHost = MYSQL_HOST; //Database host
private $dbUser = MYSQL_USER; //Username
private $dbPass = MYSQL_PASS; //Password
private $dbName = MYSQL_DB; //Database

private $con = false; //Turns true when a connection has been made
private $result = array(); //Stores the result of a query
private $sql = null; //Can store a SQL statement to be run
private $currentConn = null; //Stores the current connection details

private $autoConnect = false; //When true, a connection is made when a new instance is made
private $autoDisconnect = true; //When true, a connection is automatically disconnected when the instance is closed

/*
* Connects to the MySQL db when $autoConnect is true
*/
public function __construct() {
if($this->autoConnect) {
$this->connect();
}
}

/*
* Disconnects from a MySQL db when $autoDisconnect is true
*/
public function __destruct() {
if($this->autoDisconnect) {
$this->disconnect();
}
}

/*
* Connects to the database, only one connection allowed
*/
public function connect() {
if(!$this->con) {
$this->currentConn = @mysql_connect($this->dbHost,$this->dbUser,$this->dbPass);
if($this->currentConn) {
$seldb = @mysql_select_db($this->dbName,$this->currentConn);
if($seldb) {
$this->con = true;
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return true;
}
}

/*
* Disconnects from the database
*/
public function disconnect() {
if($this->con) {
$this->sql = null;
$this->con = false;
$this->results = null;
mysql_close($this->currentConn);
}
}

/*
* Changes the new database, sets all current results to null
*/
public function setDatabase($name) {
if($this->con) {
if(@mysql_close()) {
$this->sql = null;
$this->con = false;
$this->results = null;
$this->dbName = $name;
$this->connect();
}
}
}

/*
* Checks to see if the table exists when performing queries
*/
private function tableExists($table) {
$tablesInDb = @mysql_query('SHOW TABLES FROM '.$this->dbName.' LIKE "'.$table.'"');
if($tablesInDb) {
if(mysql_num_rows($tablesInDb)==1) {
return true;
} else {
return false;
}
}
}

/*
* Selects information from the database.
* Required: table (the name of the table)
* Optional: rows (the columns requested, separated by commas)
* where (column = value as a string)
* order (column DIRECTION as a string)
*/
public function select($table, $rows = '*', $where = null, $order = null) {
$q = 'SELECT '.$rows.' FROM '.$table;
if($where != null) {
$q .= ' WHERE '.$where;
}
if($order != null) {
$q .= ' ORDER BY '.$order;
}
$query = @mysql_query($q);
if($query) {
$this->numResults = mysql_num_rows($query);
for($i = 0; $i < $this->numResults; $i++) {
$r = mysql_fetch_array($query);
$key = array_keys($r);
for($x = 0; $x < count($key); $x++) {
// Sanitizes keys so only alphavalues are allowed
if(!is_int($key[$x])) {
if(mysql_num_rows($query) > 1) {
$this->result[$i][$key[$x]] = $r[$key[$x]];
} else if(mysql_num_rows($query) < 1) {
$this->result = null;
} else {
$this->result[$key[$x]] = $r[$key[$x]];
}
}
}
}
return true;
} else {
return false;
}
}

/*
* Insert values into the table
* Required: table (the name of the table)
* values (the values to be inserted)
* Optional: rows (if values don't match the number of rows)
*/
public function insert($table,$values,$rows = null) {
if($this->tableExists($table)) {
$insert = 'INSERT INTO '.$table;
if($rows != null) {
$insert .= ' ('.$rows.')';
}

for($i = 0; $i < count($values); $i++) {
if(is_string($values[$i])) {
$values[$i] = '"'.$values[$i].'"';
}
}
$values = implode(',',$values);
$insert .= ' VALUES ('.$values.')';

$ins = @mysql_query($insert);

if($ins) {
return true;
} else {
return false;
}
}
}

/*
* Deletes table or records where condition is true
* Required: table (the name of the table)
* Optional: where (condition [column = value])
*/
public function delete($table,$where = null) {
if($this->tableExists($table)) {
if($where == null) {
$delete = 'DELETE '.$table;
} else {
$delete = 'DELETE FROM '.$table.' WHERE '.$where;
}
$del = @mysql_query($delete);

if($del) {
return true;
} else {
return false;
}
} else {
return false;
}
}

/*
* Updates the database with the values sent
* Required: table (the name of the table to be updated
* rows (the rows/values in a key/value array
* where (the row/condition in an array (row,condition) )
*/
public function update($table,$rows,$where) {
if($this->tableExists($table)) {
// Parse the where values
// even values (including 0) contain the where rows
// odd values contain the clauses for the row
for($i = 0; $i < count($where); $i++) {
if($i%2 != 0) {
if(is_string($where[$i])) {
if(($i+1) != null) {
$where[$i] = '"'.$where[$i].'" AND ';
} else {
$where[$i] = '"'.$where[$i].'"';
}
}
}
}
$where = implode('',$where);
$update = 'UPDATE '.$table.' SET ';
$keys = array_keys($rows);
for($i = 0; $i < count($rows); $i++) {
if(is_string($rows[$keys[$i]])) {
$update .= $keys[$i].'="'.$rows[$keys[$i]].'"';
} else {
$update .= $keys[$i].'='.$rows[$keys[$i]];
}

// Parse to add commas
if($i != count($rows)-1) {
$update .= ',';
}
}
$update .= ' WHERE '.$where;
$query = @mysql_query($update);
if($query) {
return true;
} else {
return false;
}
} else {
return false;
}
}

/*
* Returns the result set
*/
public function getResult() {
return $this->result;
}

/*
* Store a SQL statement to be ran
* Required: $query (the query to be stored)
*/
public function setSQL($query) {
$this->sql = $query;
if($this->sql != $query) {
return false;
} else {
return true;
}
}

/*
* Run the stored SQL statement
*/
public function runSQL() {
$this->result = mysql_query($this->sql);
}
}
?>
[/syntax]

Is there anything you think I am missing from this?
I can't think of anything witty to put here!

Check out some of my projects on GitHub: https://github.com/DomTC
Post Reply