mysql 自动过滤简单的代码:
<?php
/**
*
*/
class sql
{
function __construct()
{
# code...
}
public function add_special_char(&$value) {
if('*' == $value || false !== strpos($value, '(') || false !== strpos($value, '.') || false !== strpos ( $value, '`')) {
//不处理包含* 或者 使用了sql方法。
} else {
$value = '`'.trim($value).'`';
}
if (preg_match("/\b(select|insert|update|delete)\b/i", $value)) {
$value = preg_replace("/\b(select|insert|update|delete)\b/i", '', $value);
}
return $value;
}
public function escape_string(&$value, $key='', $quotation = 1) {
if ($quotation) {
$q = '\'';
} else {
$q = '';
}
$value = $q.$value.$q;
return $value;
}
public function sql() {
$array = array(
"name" => 'Name 1',
"value" => 'Value 1',
"other_value" => 'a(Other 1)a',
);
$table = "`example`";
// 获取字段
$fields = array_keys($array);
array_walk($fields, array($this, 'add_special_char'));
$fields = join(',',$fields );
// 获取值
$values = array_values($array);
array_walk($values, array($this, 'escape_string'));
$values = join(',', $values);
$sql = "INSERT {$table}($fields) VALUES({$values})";
echo $sql;
}
}
$sql = new sql();
$sql->sql();