0

How can I use PHP preg_match for a string to check if it contains any sql? Not for preventing SQL injection but just to tell if it contains a sql statement

poashoas
  • 1,790
  • 2
  • 21
  • 44
  • You can't. You can look for some SQL specific keywords, but to check if its valid SQL you need some heavier logic. – SBH Nov 17 '14 at 17:58
  • You could try to execute the query and get the return of that execute in a variable. You could set up a test database for these queries so your actual data isn't compromised. – Triplus Nov 17 '14 at 18:07
  • 1
    `$sql = 's' . 'e' . 'l' . 'e' . 'c' . 't' . 'etc...'`. There's a string that contains some SQL...good luck coming up with a regex that could detect every potential variation of that... – Marc B Nov 17 '14 at 18:09

1 Answers1

3

Checking a string for SQL is not worth your time or resources for that matter. If the goal is to prevent injection you should use PDO.

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute(array('name' => $name));

foreach ($stmt as $row) {
    // do something with $row
}

Reference material: How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Edwin
  • 1,135
  • 2
  • 16
  • 24