Skip to content

Instantly share code, notes, and snippets.

@bkilshaw
Created May 6, 2011 05:59
Show Gist options
  • Save bkilshaw/958509 to your computer and use it in GitHub Desktop.
Save bkilshaw/958509 to your computer and use it in GitHub Desktop.
PHP SQLQuery Class
<?php
// Run a query and return results
class SQLQuery {
public $query = "";
private $allowed_query_types = array(
'INSERT'
, 'DELETE'
, 'UPDATE'
, 'SELECT'
);
// To let us run without instantiating; eg: $results = SQLQuery::query($query);
public function query($query) {
$result = new SQLQuery($query);
return $result->results;
}
public function __construct($query) {
$this->query = trim($query);
// Get the type of query (insert, delete, update, select) so we know how to handle results
$query_type = $this->get_query_type();
// Check to make suer its an 'allowed' query type
if(in_array($query_type, $this->allowed_query_types)) {
$this->execute_query();
// Dynamically runs the method we got before to handle results appropriatly
$this->$query_type();
} else {
$this->results = FALSE;
}
}
public function get_query_type() {
// We're just checking the first word of the query to get the query type
$query_parts = explode(" ", $this->query);
$query_type = strtoupper($query_parts[0]);
return $query_type;
}
public function execute_query() {
// Run query
$this->query_results = mysql_query($this->query);
}
public function insert() {
// If the query was succesfull return the insert ID, if not return false
if($this->query_results) {
$this->results = mysql_insert_id();
} else {
$this->results = FALSE;
}
}
public function select() {
$return_array = array();
if($this->query_results) {
// If there's no results return an emty array
if(mysql_num_rows($this->query_results) == 0) {
$this->results = array();
// If there's only one result return it directly
} else if (mysql_num_rows($this->query_results) == 1) {
$this->results = mysql_fetch_assoc($this->query_results);
// Or if there's many results return an array of them all
} else {
while ($row = mysql_fetch_assoc($this->query_results)) {
$return_array[] = $row;
}
$this->results = $return_array;
}
} else {
$this->results = array();
}
}
public function delete() {
// Return results directly, will be TRUE | FALSE
$this->results = $this->query_results;
}
public function update() {
// Return results directly, will be TRUE | FALSE
$this->results = $this->query_results;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment