-1

I'm using MySQL like so for executing queries:

public function query($query, $params = array(), $format = array()) {

    if ( !is_array( $params ) ) return false;

    $dbh = parent::$dbh;

    if ( empty($dbh) ) return false;

    $stmt = $dbh->prepare($query);

    if ( !empty($format)) {
        $values = array_values($params);
        foreach ( $format as $key => $bind ) {
            switch ($bind) {
                case '%d':
                    $stmt->bindValue($key + 1, $values[$key], PDO::PARAM_INT);
                    break;
                case '%s':
                    $stmt->bindValue($key + 1, $values[$key], PDO::PARAM_STR);
                    break;
                default:
                    $stmt->bindValue($key + 1, $values[$key], PDO::PARAM_STR);
                    break;
            }

        }
    }

    $stmt->execute($params);

    return $stmt;

}

How can I safely remove invalid characters from a search that uses LIKE:

For instance:

 $filter = "filter's";

 if (isset($filter)) {
    $search_filter = 'content LIKE \'%'.$filter.'%\'';

    $sql = "SELECT $search_filter FROM  messages";

    $stmt = $this->query($sql);
}
Paul
  • 11,671
  • 32
  • 91
  • 143

2 Answers2

2

I am not sure I am following your sophisticated code, but something like this

$filter = "filter's";

$params = array();
$sql = "SELECT * FROM messages";
if (isset($filter)) {
    $sql .= ' WHERE content LIKE ?';
    $params[] = "%$filter%";
} 
$stmt = $this->query($sql, $params);

the idea is to create a query with placeholders dynamically but keep all variable parts go via placeholders only.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
1

The simplest way is to use PDO::quote

Change the assignment of $search_field

$search_filter = 'content like '.$dbh->quote("%".$filter."%");

If you want to move to parameterized queries you would do

$sql = "select * from messages where content like ?";
$params = "%".$filter."%";
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
Orangepill
  • 24,500
  • 3
  • 42
  • 63