0

Is this query secure from sql injection ?

And a must in every function to write $connection->close();?

function insert_mytable() {
    global $connection; 

    $text = 'bla bla';
    $hashtag = 'bla bla';

    // Prepare the statement
    $stmt = $connection->prepare("INSERT INTO my_table (text, hashtag) VALUES (?, ?)");
    $stmt->bind_param('ss', $text, $hashtag);

    // Execute the statement
    $stmt->execute();

    // Close the statement
    $stmt->close();
    $connection->close();
}
Dharman
  • 21,838
  • 18
  • 57
  • 107

1 Answers1

2

To answer your first question: Yes*

*Since you are using prepared statements, your code is safe from SQL injection attacks in most cases. It is likely the case that, for your purpose, the above code is all the defense you require against SQL injection; however, if you wish to know in what cases prepared statements are not sufficient, you should look at the first answer to this question as Joel Coehoorn explains it far better than I.

As far as your second question, as ac.freelancer and Charlotte Dunois have already pointed out, the connection does not need to be closed, especially not if you intend to use the connection again.

Dharman
  • 21,838
  • 18
  • 57
  • 107
Kyte Aryus
  • 161
  • 4