Skip to content

Instantly share code, notes, and snippets.

@StokicDusan
Last active October 16, 2021 11:39
Show Gist options
  • Save StokicDusan/07ce7876ea0bef074359c368e08b9704 to your computer and use it in GitHub Desktop.
Save StokicDusan/07ce7876ea0bef074359c368e08b9704 to your computer and use it in GitHub Desktop.
Preventing an SQL injection attack in PHP using prepared statements

A way you can protect your code against SQL injections is using prepared statements.
Prepared statements are precompiled SQL commands.
Using MySQLi Object-Oriented:

<?php
 $conn = new mysqli($servername, $username, $password, $dbname);

 $query = $conn->prepare('SELECT * FROM student WHERE name = ?');
 $query->bind_param('s', $name); // 's' specifies the variable type string
 $query->execute();

 $result = $query->get_result();
 while ($row = $result->fetch_assoc()) {
     // Do something with $row
 }
 
 $conn->close();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment