0

Previously I used general mysqli queries to insert values in database with real_escape_string for security but everyone seems to use prepared statements for better security. To increase security and prevent sql injection I am going to replace my code with prepared statements but I wanted to know that how much secure is prepared statement given below. Can you suggest any more improvement for better security?

$stmt = mysqli_prepare($DB_connection,"INSERT INTO `posts`(`example`, `example2`) VALUES ('$for_example',?)");
    mysqli_stmt_bind_param($stmt, 's', $_POST['username']);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);

I get values from a form using POST method and add them to database. Can users replace values in database by sql injection?
Thanks for any help in advance.

haim770
  • 48,394
  • 7
  • 105
  • 133
mwaseema
  • 118
  • 10

1 Answers1

1

From PHP manual:

The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

Reference: Prepared statements and stored procedures

You ARE building your query with (possibly) unescaped input. It all depends whether or not $for_example is safe...

Therefore, my suggestion would be to include $for_example as a parameter in your prepared statement.

Marty McVry
  • 2,838
  • 1
  • 17
  • 23