Skip to content

Instantly share code, notes, and snippets.

@grakic
Last active December 12, 2015 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grakic/4773155 to your computer and use it in GitHub Desktop.
Save grakic/4773155 to your computer and use it in GitHub Desktop.
A small mysqli wrapper to prevent SQLi
<?php
class mysqli extends \mysqli {
// ...
public function safe_query($query)
{
$args = array_slice(func_get_args(), 1);
$safe_sql = $this->format_query($query, $args);
return $this->query($safe_sql);
}
public function format_query($sql, $args = null)
{
if(is_null($args)) return $sql;
preg_match_all("/%(\d+\$)?[-+]?('.|0| )?a?\d*(\.\d*)?([bcdeEufFgGosxX])/", $sql, $matches, PREG_PATTERN_ORDER);
if(count($matches[1]) != count($args))
trigger_error('Invalid query arguments, expecting '.count($matches[1]).' arguments but '.count($args).' given.');
$matches = $matches[count($matches)-1];
for($i = 0; $i < count($matches); $i++)
{
switch($matches[$i])
{
case 'd':
$args[$i] = intval($args[$i]);
break;
case 'f':
$args[$i] = floatval($args[$i]);
break;
case 's':
$args[$i] = "'".$this->real_escape_string($args[$i])."'";
break;
default:
trigger_error('Unknown query argument format "'.$matches[$i].'"');
}
}
return vsprintf($sql, $args);
}
}
// Demo
$mysqli = new mysqli;
if($mysqli->connect_errno)
echo 'Failed to connect to MySQL: '.$mysqli->connect_error;
$user_id = isset($_GET['userid']) ? $_GET['userid'] : 1;
$query = 'SELECT user_tel, user_email FROM users WHERE user_id = %d';
// Fetch Value
$result = $mysqli->safe_query($query, $user_id);
while ($statement->fetch()) {
echo "Tel: ".$tel."\n";
echo "Email: ".$email."<br />\n";
}
$mysqli->close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment