2

I'm trying to filter out as much as possible to prevent nasty SQL injection, here's my code example, is there anything I'm missing?

$name = htmlspecialchars($row['name']);
echo '<div class="col-sm-7">'.$name.'</div>';

in my html code ^

if( $_POST["name"] ) {
 if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
     die ("Invalid characters.");
}

$name = mysqli_real_escape_string($conn, trim($_POST['name']));

so my codes include these above, is there anything I'm missing that could prevent further?

One more question

So do I have to filter out my own definition since this data is not come from my form? e.g.

$currentdate = mysqli_real_escape_string($conn, trim(date("Y-m-d h:i:sa")));

DagicCross
  • 401
  • 3
  • 13
  • 5
    Then USE PREPARED STATEMENT with SUBSTITUTION PARAMETERS – RiggsFolly Jan 30 '16 at 16:18
  • You don't have to filter out any "invalid characters", that does not make any sense. Use escaping (as you already do) or, even better, use "prepared statements" and "parameter binding". – arkascha Jan 30 '16 at 16:20
  • And look at the `filter_` set of functions in [the manual](http://php.net/manual/en/book.filter.php) – RiggsFolly Jan 30 '16 at 16:20
  • Yes, have a look at PDO for querying the database. Or even an ORM (propel/doctrine) if you've got many tables and want to be able to manipulate database entites easily in your coce – David Jan 30 '16 at 16:20
  • is that `pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"` in html code? – DagicCross Jan 30 '16 at 16:23

1 Answers1

3

Personally I think that you're fine for SQL injection, but I'd take a look at what some of the people are saying in the comments.

On another note, unrelated to SQL injection, you might want to consider using strip_tags on $name as well to strip out any unwanted HTML characters.

JThistle
  • 128
  • 1
  • 9