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