sql injection image

What is SQL injection attack?

A SQL injection attack is a way of inserting or injecting a sql query via the input data from the client side of an application/website so as to make a sql query function differently from it intended purpose and cause sql database to perform differently from it intended purpose by an attacker.

Example of an sql attack is describe in the picture below;

sql injection image

The intended query should look like “select * from users where user_id = ‘myusername’ and password = ‘mypassword’ limit 1 “ but for an attack, the input fed to the sql will be one that can cause trouble, though sql will see it as a valid query. Example is “select * from users where user_id=” OR 1 = 1;/*’ and password = ‘*/–‘ “. What this query does is that even though there is no username with empty , the application will run true and the attacker will gain access to the website or application to cause further damages.


So, to avoid this problem, I will be showing one way to prevent sql injection using php-mysql approach in this tutorials. See steps below:

-> Assuming you will be receiving inputs from users such as username or password, topic, category and other kinds of input, expect that there could be attack, so, write code that will prevent it.

I will be using php prepared statement to prevent this attack. In php-sql prepared statement, the input from users is not communicating with the database directly. So, any inputs from user is treated as mere string.

The example below shows a php function to check if login exist and respond accordingly using php prepared statement.

public function check2login($username, $password)
$conn = $this->connect();
$stmt1 = "select username, password from user_table where (username = ? and password = ?) limit 1";

$prep1 = $conn->prepare($stmt1);//prepare the statement.
$prep1->bind_param('ss', $username, $password);//;//bind each variable to expected character to be received
$prep1->execute();//execute command.
$prep1->store_result();//store results.
if($prep1->num_rows == 1){
echo 'y';//login success

echo 'n';//failed login, not exist probably.

In the code snippet above, irrespective of whatever the user sends, the sql command first run, create a result pool, then compares it with whatever the user sent. So, there is no way user can inject dangerous sql code to cause trouble and your app is save from trouble.


If there are any contributions, or issues, or explanations, you can use the comment section or email @NaijaTech


See Post on app that talks to the internet via php, mysql technology



This is NaijaTech