Commit 5f443c88 authored by Josh Campbell's avatar Josh Campbell

Merge pull request #7 from Gemorroj/master

code review (psr1/psr2, charset)
parents 2a19a70c d5e2a79c
<?php <?php
/** /**
* MySqliDb Class * MysqliDb Class
* *
* @category Database Access * @category Database Access
* @package MysqliDB * @package MysqliDb
* @author Jeffery Way <jeffrey@jeffrey-way.com> * @author Jeffery Way <jeffrey@jeffrey-way.com>
* @author Josh Campbell <jcampbell@ajillion.com> * @author Josh Campbell <jcampbell@ajillion.com>
* @copyright Copyright (c) 2010 * @copyright Copyright (c) 2010
* @license http://opensource.org/licenses/gpl-3.0.html GNU Public License * @license http://opensource.org/licenses/gpl-3.0.html GNU Public License
* @version 1.1 * @version 1.1
**/ **/
class MysqliDB { class MysqliDb
{
/** /**
* Static instance of self * Static instance of self
* *
* @var object * @var MysqliDb
*/ */
protected static $_instance; protected static $_instance;
/** /**
* MySQLi instance * MySQLi instance
* *
* @var object * @var mysqli
*/ */
protected $_mysqli; protected $_mysqli;
/** /**
* The SQL query to be prepared and executed * The SQL query to be prepared and executed
* *
* @var object * @var string
*/ */
protected $_query; protected $_query;
/** /**
...@@ -55,9 +55,19 @@ class MysqliDB { ...@@ -55,9 +55,19 @@ class MysqliDB {
*/ */
protected $_bindParams = array(''); // Create the empty 0 index protected $_bindParams = array(''); // Create the empty 0 index
public function __construct($host, $username, $password, $db) { /**
* @param string $host
* @param string $username
* @param string $password
* @param string $db
*/
public function __construct($host, $username, $password, $db)
{
$this->_mysqli = new mysqli($host, $username, $password, $db) $this->_mysqli = new mysqli($host, $username, $password, $db)
or die('There was a problem connecting to the database'); or die('There was a problem connecting to the database');
$this->_mysqli->set_charset('utf8');
self::$_instance = $this; self::$_instance = $this;
} }
...@@ -93,47 +103,47 @@ class MysqliDB { ...@@ -93,47 +103,47 @@ class MysqliDB {
* Pass in a raw query and an array containing the parameters to bind to the prepaird statement. * Pass in a raw query and an array containing the parameters to bind to the prepaird statement.
* *
* @param string $query Contains a user-provided query. * @param string $query Contains a user-provided query.
* @param array $bindData All variables to bind to the SQL statment. * @param array $bindParams All variables to bind to the SQL statment.
*
* @return array Contains the returned rows from the query. * @return array Contains the returned rows from the query.
*/ */
public function rawQuery($query, $bindParams = NULL) public function rawQuery($query, $bindParams = null)
{ {
$this->_query = filter_var($query, FILTER_SANITIZE_STRING); $this->_query = filter_var($query, FILTER_SANITIZE_STRING);
$stmt = $this->_prepareQuery(); $stmt = $this->_prepareQuery();
if (gettype($bindParams) === 'array') { if (is_array($bindParams) === true) {
$params = array(''); // Create the empty 0 index $params = array(''); // Create the empty 0 index
foreach ($bindParams as $prop => $val) { foreach ($bindParams as $prop => $val) {
$params[0] .= $this->_determineType($val); $params[0] .= $this->_determineType($val);
array_push($params, $bindParams[$prop]); array_push($params, $bindParams[$prop]);
} }
call_user_func_array(array($stmt, "bind_param"),$this->refValues($params)); call_user_func_array(array($stmt, 'bind_param'), $this->refValues($params));
} }
$stmt->execute(); $stmt->execute();
$this->reset(); $this->reset();
$results = $this->_dynamicBindResults($stmt); return $this->_dynamicBindResults($stmt);
return $results;
} }
/** /**
* *
* @param string $query Contains a user-provided select query. * @param string $query Contains a user-provided select query.
* @param int $numRows The number of rows total to return. * @param int $numRows The number of rows total to return.
*
* @return array Contains the returned rows from the query. * @return array Contains the returned rows from the query.
*/ */
public function query($query, $numRows = NULL) public function query($query, $numRows = null)
{ {
$this->_query = filter_var($query, FILTER_SANITIZE_STRING); $this->_query = filter_var($query, FILTER_SANITIZE_STRING);
$stmt = $this->_buildQuery($numRows); $stmt = $this->_buildQuery($numRows);
$stmt->execute(); $stmt->execute();
$this->reset(); $this->reset();
$results = $this->_dynamicBindResults($stmt); return $this->_dynamicBindResults($stmt);
return $results;
} }
/** /**
...@@ -141,35 +151,34 @@ class MysqliDB { ...@@ -141,35 +151,34 @@ class MysqliDB {
* *
* @param string $tableName The name of the database table to work with. * @param string $tableName The name of the database table to work with.
* @param integer $numRows The number of rows total to return. * @param integer $numRows The number of rows total to return.
*
* @return array Contains the returned rows from the select query. * @return array Contains the returned rows from the select query.
*/ */
public function get($tableName, $numRows = NULL) public function get($tableName, $numRows = null)
{ {
$this->_query = "SELECT * FROM $tableName"; $this->_query = "SELECT * FROM $tableName";
$stmt = $this->_buildQuery($numRows); $stmt = $this->_buildQuery($numRows);
$stmt->execute(); $stmt->execute();
$this->reset(); $this->reset();
$results = $this->_dynamicBindResults($stmt); return $this->_dynamicBindResults($stmt);
return $results;
} }
/** /**
* *
* @param <string $tableName The name of the table. * @param <string $tableName The name of the table.
* @param array $insertData Data containing information for inserting into the DB. * @param array $insertData Data containing information for inserting into the DB.
*
* @return boolean Boolean indicating whether the insert query was completed succesfully. * @return boolean Boolean indicating whether the insert query was completed succesfully.
*/ */
public function insert($tableName, $insertData) public function insert($tableName, $insertData)
{ {
$this->_query = "INSERT into $tableName"; $this->_query = "INSERT into $tableName";
$stmt = $this->_buildQuery(NULL, $insertData); $stmt = $this->_buildQuery(null, $insertData);
$stmt->execute(); $stmt->execute();
$this->reset(); $this->reset();
($stmt->affected_rows) ? $result = $stmt->insert_id : $result = false; return ($stmt->affected_rows > 0 ? $stmt->insert_id : false);
return $result;
} }
/** /**
...@@ -177,18 +186,18 @@ class MysqliDB { ...@@ -177,18 +186,18 @@ class MysqliDB {
* *
* @param string $tableName The name of the database table to work with. * @param string $tableName The name of the database table to work with.
* @param array $tableData Array of data to update the desired row. * @param array $tableData Array of data to update the desired row.
*
* @return boolean * @return boolean
*/ */
public function update($tableName, $tableData) public function update($tableName, $tableData)
{ {
$this->_query = "UPDATE $tableName SET "; $this->_query = "UPDATE $tableName SET ";
$stmt = $this->_buildQuery(NULL, $tableData); $stmt = $this->_buildQuery(null, $tableData);
$stmt->execute(); $stmt->execute();
$this->reset(); $this->reset();
($stmt->affected_rows) ? $result = true : $result = false; return ($stmt->affected_rows > 0);
return $result;
} }
/** /**
...@@ -196,17 +205,18 @@ class MysqliDB { ...@@ -196,17 +205,18 @@ class MysqliDB {
* *
* @param string $tableName The name of the database table to work with. * @param string $tableName The name of the database table to work with.
* @param integer $numRows The number of rows to delete. * @param integer $numRows The number of rows to delete.
*
* @return boolean Indicates success. 0 or 1. * @return boolean Indicates success. 0 or 1.
*/ */
public function delete($tableName, $numRows = NULL) { public function delete($tableName, $numRows = null)
{
$this->_query = "DELETE FROM $tableName"; $this->_query = "DELETE FROM $tableName";
$stmt = $this->_buildQuery($numRows); $stmt = $this->_buildQuery($numRows);
$stmt->execute(); $stmt->execute();
$this->reset(); $this->reset();
($stmt->affected_rows) ? $result = true : $result = false; return ($stmt->affected_rows > 0);
return $result;
} }
/** /**
...@@ -216,6 +226,8 @@ class MysqliDB { ...@@ -216,6 +226,8 @@ class MysqliDB {
* *
* @param string $whereProp The name of the database field. * @param string $whereProp The name of the database field.
* @param mixed $whereValue The value of the database field. * @param mixed $whereValue The value of the database field.
*
* @return MysqliDb
*/ */
public function where($whereProp, $whereValue) public function where($whereProp, $whereValue)
{ {
...@@ -238,11 +250,12 @@ class MysqliDB { ...@@ -238,11 +250,12 @@ class MysqliDB {
* Escape harmful characters which might affect a query. * Escape harmful characters which might affect a query.
* *
* @param string $str The string to escape. * @param string $str The string to escape.
*
* @return string The escaped string. * @return string The escaped string.
*/ */
public function escape ( $str ) public function escape($str)
{ {
return $this->_mysqli->real_escape_string ( $str ); return $this->_mysqli->real_escape_string($str);
} }
/** /**
...@@ -252,6 +265,7 @@ class MysqliDB { ...@@ -252,6 +265,7 @@ class MysqliDB {
* and then updates the param_type. * and then updates the param_type.
* *
* @param mixed $item Input to determine the type. * @param mixed $item Input to determine the type.
*
* @return string The joined parameter types. * @return string The joined parameter types.
*/ */
protected function _determineType($item) protected function _determineType($item)
...@@ -274,6 +288,7 @@ class MysqliDB { ...@@ -274,6 +288,7 @@ class MysqliDB {
return 'd'; return 'd';
break; break;
} }
return '';
} }
/** /**
...@@ -283,50 +298,42 @@ class MysqliDB { ...@@ -283,50 +298,42 @@ class MysqliDB {
* *
* @param int $numRows The number of rows total to return. * @param int $numRows The number of rows total to return.
* @param array $tableData Should contain an array of data for updating the database. * @param array $tableData Should contain an array of data for updating the database.
* @return object Returns the $stmt object. *
* @return mysqli_stmt Returns the $stmt object.
*/ */
protected function _buildQuery($numRows = NULL, $tableData = NULL) protected function _buildQuery($numRows = null, $tableData = null)
{ {
(gettype($tableData) === 'array') ? $hasTableData = true : $hasTableData = false; $hasTableData = is_array($tableData);
(!empty($this->_where )) ? $hasConditional = true : $hasConditional = false; $hasConditional = !empty($this->_where);
// Did the user call the "where" method? // Did the user call the "where" method?
if (!empty($this->_where)) { if (!empty($this->_where)) {
// if update data was passed, filter through and create the SQL query, accordingly. // if update data was passed, filter through and create the SQL query, accordingly.
if ($hasTableData) { if ($hasTableData) {
$i = 1;
$pos = strpos($this->_query, 'UPDATE'); $pos = strpos($this->_query, 'UPDATE');
if ( $pos !== false) { if ($pos !== false) {
foreach ($tableData as $prop => $value) { foreach ($tableData as $prop => $value) {
// determines what data type the item is, for binding purposes. // determines what data type the item is, for binding purposes.
$this->_paramTypeList .= $this->_determineType($value); $this->_paramTypeList .= $this->_determineType($value);
// prepares the reset of the SQL query. // prepares the reset of the SQL query.
($i === count($tableData)) ? $this->_query .= ($prop . ' = ?, ');
$this->_query .= $prop . ' = ?':
$this->_query .= $prop . ' = ?, ';
$i++;
} }
$this->_query = rtrim($this->_query, ', ');
} }
} }
//Prepair the where portion of the query //Prepair the where portion of the query
$this->_query .= ' WHERE '; $this->_query .= ' WHERE ';
$i = 1;
foreach ($this->_where as $column => $value) { foreach ($this->_where as $column => $value) {
// Determines what data type the where column is, for binding purposes. // Determines what data type the where column is, for binding purposes.
$this->_whereTypeList .= $this->_determineType($value); $this->_whereTypeList .= $this->_determineType($value);
// Prepares the reset of the SQL query. // Prepares the reset of the SQL query.
($i === count($this->_where)) ? $this->_query .= ($column . ' = ? AND ');
$this->_query .= $column . ' = ?':
$this->_query .= $column . ' = ? AND ';
$i++;
} }
$this->_query = rtrim($this->_query, ' AND ');
} }
// Determine if is INSERT query // Determine if is INSERT query
...@@ -348,15 +355,17 @@ class MysqliDB { ...@@ -348,15 +355,17 @@ class MysqliDB {
$this->_query .= '(' . implode($keys, ', ') . ')'; $this->_query .= '(' . implode($keys, ', ') . ')';
$this->_query .= ' VALUES('; $this->_query .= ' VALUES(';
while ($num !== 0) { while ($num !== 0) {
($num !== 1) ? $this->_query .= '?, ' : $this->_query .= '?)'; $this->_query .= '?, ';
$num--; $num--;
} }
$this->_query = rtrim($this->_query, ', ');
$this->_query .= ')';
} }
} }
// Did the user set a limit // Did the user set a limit
if (isset($numRows)) { if (isset($numRows)) {
$this->_query .= " LIMIT " . (int) $numRows; $this->_query .= ' LIMIT ' . (int)$numRows;
} }
// Prepare query // Prepare query
...@@ -370,7 +379,7 @@ class MysqliDB { ...@@ -370,7 +379,7 @@ class MysqliDB {
} }
} }
// Prepare where condition bind parameters // Prepare where condition bind parameters
if($hasConditional) { if ($hasConditional) {
if ($this->_where) { if ($this->_where) {
$this->_bindParams[0] .= $this->_whereTypeList; $this->_bindParams[0] .= $this->_whereTypeList;
foreach ($this->_where as $prop => $val) { foreach ($this->_where as $prop => $val) {
...@@ -379,8 +388,8 @@ class MysqliDB { ...@@ -379,8 +388,8 @@ class MysqliDB {
} }
} }
// Bind parameters to statment // Bind parameters to statment
if ($hasTableData || $hasConditional){ if ($hasTableData || $hasConditional) {
call_user_func_array(array($stmt, "bind_param"),$this->refValues($this->_bindParams)); call_user_func_array(array($stmt, 'bind_param'), $this->refValues($this->_bindParams));
} }
return $stmt; return $stmt;
...@@ -390,10 +399,11 @@ class MysqliDB { ...@@ -390,10 +399,11 @@ class MysqliDB {
* This helper method takes care of prepared statements' "bind_result method * This helper method takes care of prepared statements' "bind_result method
* , when the number of variables to pass is unknown. * , when the number of variables to pass is unknown.
* *
* @param object $stmt Equal to the prepared statement object. * @param mysqli_stmt $stmt Equal to the prepared statement object.
*
* @return array The results of the SQL fetch. * @return array The results of the SQL fetch.
*/ */
protected function _dynamicBindResults($stmt) protected function _dynamicBindResults(mysqli_stmt $stmt)
{ {
$parameters = array(); $parameters = array();
$results = array(); $results = array();
...@@ -402,11 +412,11 @@ class MysqliDB { ...@@ -402,11 +412,11 @@ class MysqliDB {
$row = array(); $row = array();
while ($field = $meta->fetch_field()) { while ($field = $meta->fetch_field()) {
$row[$field->name] = NULL; $row[$field->name] = null;
$parameters[] = &$row[$field->name]; $parameters[] = & $row[$field->name];
} }
call_user_func_array(array($stmt, "bind_result"),$parameters); call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) { while ($stmt->fetch()) {
$x = array(); $x = array();
...@@ -421,27 +431,38 @@ class MysqliDB { ...@@ -421,27 +431,38 @@ class MysqliDB {
/** /**
* Method attempts to prepare the SQL query * Method attempts to prepare the SQL query
* and throws an error if there was a problem. * and throws an error if there was a problem.
*
* @return mysqli_stmt
*/ */
protected function _prepareQuery() protected function _prepareQuery()
{ {
if (!$stmt = $this->_mysqli->prepare($this->_query)) { if (!$stmt = $this->_mysqli->prepare($this->_query)) {
trigger_error("Problem preparing query ($this->_query) ".$this->_mysqli->error, E_USER_ERROR); trigger_error("Problem preparing query ($this->_query) " . $this->_mysqli->error, E_USER_ERROR);
} }
return $stmt; return $stmt;
} }
/**
* Close connection
*/
public function __destruct() public function __destruct()
{ {
$this->_mysqli->close(); $this->_mysqli->close();
} }
function refValues($arr) /**
* @param array $arr
*
* @return array
*/
protected function refValues($arr)
{ {
//Reference is required for PHP 5.3+ //Reference is required for PHP 5.3+
if (strnatcmp(phpversion(),'5.3') >= 0) { if (strnatcmp(phpversion(), '5.3') >= 0) {
$refs = array(); $refs = array();
foreach($arr as $key => $value) foreach ($arr as $key => $value) {
$refs[$key] = &$arr[$key]; $refs[$key] = & $arr[$key];
}
return $refs; return $refs;
} }
return $arr; return $arr;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment