Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using prepared statements in MySQL prevent SQL injection attacks?

I'd just like to verify if using prepared statements in MySQL prevents SQL injection.

Will the following code prevent all SQL injection attacks?

$var = $_GET['q']; 
$trimmed = trim($var);
if ($trimmed != NULL) {
  $get_fighters = $DBH->prepare(
    'SELECT * 
    FROM fighters 
    WHERE name LIKE :searchTerm 
      OR nickname LIKE :searchTerm 
      OR born_in_city LIKE :searchTerm
      OR born_in_state LIKE :searchTerm
      OR born_in_country LIKE :searchTerm
      ORDER BY name ASC');
  $get_fighters->bindValue(':searchTerm', '%' . $trimmed . '%', PDO::PARAM_STR);
  $get_fighters->setFetchMode(PDO::FETCH_ASSOC);
  $get_fighters->execute();
  $check_results_fighters = $get_fighters->rowCount();

  $get_events = $DBH->prepare(
    'SELECT * 
    FROM events 
    WHERE event_name LIKE :searchTerm
      OR event_arena LIKE :searchTerm
      OR event_city LIKE :searchTerm
      OR event_state LIKE :searchTerm
      OR event_country LIKE :searchTerm
      OR organization LIKE :searchTerm
    ORDER BY event_date DESC');

  $get_events->bindValue(':searchTerm', '%' . $trimmed . '%', PDO::PARAM_STR);
  $get_events->setFetchMode(PDO::FETCH_ASSOC);
  $get_events->execute();
  $check_results_events = $get_events->rowCount(); 
}
like image 233
zen Avatar asked Dec 27 '22 23:12

zen


1 Answers

Prepared queries prevent attacks by separating the query to be ran, and the data to be used for that query. That means that a first-order attack cannot occur, since you're not concatenating data directly into the query.

In short, if you always use prepared queries, and all of your data is sent with bound parameters (including data from other queries!) then you are fine, as far as SQL injection goes.

(I should also note that some PDO drivers for servers that do not support prepared queries will fake it with traditional escape routines. Don't concern yourself with this. It's safe.)

like image 93
Brad Avatar answered Jan 13 '23 13:01

Brad