Skip to content
Permalink
Browse files Browse the repository at this point in the history
add SQL injection preventor
  • Loading branch information
gmtranthanhtu committed Jan 13, 2015
1 parent 8b688a6 commit 194a041
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions library/Database.php
Expand Up @@ -22,6 +22,10 @@ function getAffectedRows()
return mysqli_affected_rows($this->connection);
}

function sqlInjectionPrevent($value) {
return mysqli_real_escape_string($this->connection, $value);
}

function query($sql) {
$queryData = $this->connection->query($sql);
if(!$this->getAffectedRows()) return false;
Expand All @@ -40,7 +44,7 @@ function where($where = array())
if(count($where)) {
$arrTempWhere = array();
foreach($where as $key => $value) {
if(is_string($value)) $arrTempWhere[] = '' . $key . " = '" . $value . "'";
if(is_string($value)) $arrTempWhere[] = '' . $key . " = '" . $this->sqlInjectionPrevent($value) . "'";
else $arrTempWhere[] = '' . $key . " = " . $value;
}
$strWhere = implode(' AND ', $arrTempWhere);
Expand All @@ -55,6 +59,7 @@ function select($columns = array(), $table = '', $where = array())
if($columns === array()) $sql .= '*';
else $sql .= implode(',', $columns);
$sql .= ' FROM ' . $table . ' ' . $this->where($where);
var_dump($sql);
return $this->query($sql);
}

Expand All @@ -65,7 +70,7 @@ function insert($values = array(), $table = '')
$arrValues = array();
foreach($values as $key => $value) {
$arrKeys[] = $key;
if(is_string($value)) $arrValues[] = " '$value' ";
if(is_string($value)) $arrValues[] = " '" . $this->sqlInjectionPrevent($value) . "' ";
else $arrValues[] = "$value";
}
$sql .= implode(',', $arrKeys) . ') VALUES (' . implode(',', $arrValues) . ')';
Expand All @@ -83,7 +88,7 @@ function update($values = array(), $table = '', $where = array())
{
$arrTempValue = array();
foreach($values as $key => $value) {
if(is_string($value)) $arrTempValue[] = "$key = '$value' ";
if(is_string($value)) $arrTempValue[] = "$key = '" . $this->sqlInjectionPrevent($value) . "' ";
else $arrTempValue[] = "$key = $value";
}
$strValue = implode(',', $arrTempValue);
Expand Down

0 comments on commit 194a041

Please sign in to comment.