Search code examples
phpmysqlsqlpreg-matchhtmlspecialchars

What am I missing? SQL injection


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")));


Solution

  • 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.