0

I have a this query:

$query="select * from news where news_id = (select max(news_id) from news where news_id< $id)";

for execute I use class. in this class

public function query($query) 
{
  $this->_query = filter_var($query, FILTER_SANITIZE_STRING);
  $stmt = $this->_prepareQuery();
  $stmt->execute();
  $results = $this->_dynamicBindResults($stmt);
  return $results;
}

Is there any way that < signal is not filtered?

Testuser
  • 1,717
  • 2
  • 16
  • 24
  • You may start from this answer http://stackoverflow.com/a/14110189/285587 or this question in general http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php – Your Common Sense Jan 06 '13 at 11:45

1 Answers1

3

Unfortunately, the whole idea is wrong. FILTER_SANITIZE_STRING won't help even slightest. Let alone it just breaks your SQL.

To protect SQL from injection you must use prepared statements. So instead of adding a variable directly to the query, add a question mark. And then put this variable into execute like this

public function query($query, $params) 
{
    $stmt = $this->mysqli->prepare();
    $types = $types ?: str_repeat("s", count($params));
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    return $stmt->get_result();
}

then just use it this way

$query="select * from news where news_id = (select max(news_id) from news where news_id<?)";
$data = $db->query($query, [$id])->fetch_all(MYSQLI_ASSOC)
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345