SQL Injection Prevention in PHP

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0yf2YjeTGzat1ahVjwgEUqbf_cldlYWIPjjPKUcUsjtywjG4kAOyiLsJ61S3UXSK0C5cLDtd7OAtJEwHmiJORS7ZPwX4UrTJPG6Oeghjrh8xMAGN5qyokwyK05ppmze50ltqebZfIkDw/s400/sql-injeection-revo-brain.jpg
SQL Injection is a technique to breach the login page on website. Many websites used username and password login as "standard" authentification step and stored their user account in SQL database server. This is a simple flow chart which is describing how login username and password work :
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjuQtPcHIAIT81GTgFAFRstcAdhpGfRgaIj5hxiLt0FiJKFS9B3Ju8d2N5LvwjvVGWouZbqRzAkJ-ycX3SpaAe3XIJ561tIA5UEv1Op5MPi-3fF7Pr_SAIVQphCPJtK-IHrp_Yr_7Ioy8I/s400/Login-Flow-Chart-Revo-Brain.jpg

The question is, how does hacker breach it with SQL Injection? There are many ways from hackers to do it and just play in logical statement of SQL Query which is sent from HTML page as text/string data.
As example that in SQL Query, ""="" is always True. In normal condition on server code :
 $uName = $_POST['username'];  
 $uPass = $_POST['password'];  
 $sql = mysql_query("select * from access where username = '$uName' and password = '$uPass'");  

A smart hacker might get access to user names and passwords in a database by simply inserting " or ""=" into the user name or password text box.
The code at the server will create a valid SQL statement like this:
 select * from access where username ="" or ""="" and password ="" or ""=""  
The result SQL is valid. It will return all rows from the table access, since WHERE ""="" is always true.

How do we prevent SQL Injection?

 You could use mySQLi code in your database. This is an example about mySQLi implementation and you can change it based on your application :


 $uName = $_POST['username'];   
  if ($stmt = $mysqli->prepare("SELECT password FROM access WHERE username=?")) {   
   // Bind a variable to the parameter as a string.    
   $stmt->bind_param("s", $uName);   
   // Execute the statement.   
   $stmt->execute();   
   // Get the variables from the query.   
   $stmt->bind_result($uPass);   
   // Fetch the data.   
   $stmt->fetch();   
   // Display the data.   
   printf("Welcome back, ", $uName);   
   // Close the prepared statement.   
   $stmt->close();   
  }else {  
   printf("Sorry, I don't know you.");   
  }  

Comments