SQL injection

How to use SQL Injection in PHP?


SQL Injection is a technique where an attacker creates or alters existing SQL commands or query to retrieve information from the database in an unauthorized way. or even to execute dangerous system commands on the database.

This is accomplished by taking user input and combining it with static parameters to build an SQL query.

File Name :

If user input is inserted without changes into an SQL query, then the application becomes vulnerable to SQL injection. Example

$unsafe_var = $_POST['userinput'];
mysqli_query("INSERT INTO `itechxpert` (`column`) VALUES ('$unsafe_var')");

// above query is unsafe.
That's because the user can input something like value'); DROP TABLE itechxpert;--, and the query becomes:
INSERT INTO `itechxpert` (`column`) VALUES('value'); DROP TABLE itechxpert;--')

if you use correct way to avoid SQL injection attacks. you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL in your query..

File Name :

You have two options to achieve this mysql injection prevent :

  • Using PDO
  • Using MySQLi

  • Using PDO

    $stmt = $pdo->prepare('SELECT * FROM itechxpert WHERE name = :name');
    $stmt->execute([ 'name' => $name ]);
    foreach ($stmt as $row) {
    // write something with $row
    }

    Using Mysqli

    $stmt = $conn->prepare('SELECT * FROM itechxpert WHERE name = ?');
    $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
    // Do something with $row
    }
    https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
    https://developer.okta.com/blog/2020/06/15/sql-injection-in-php

    use this function to prevent mysql injection.

    File Name :

    $unsafe_var = $_POST["user-input"];
    $safe_var = mysql_real_escape_string($unsafe_var);

    mysqli_query("INSERT INTO ittutorial (column) VALUES ('" . $safe_var . "')");

    How to prevent mysql injection.

    File Name :

    $bad_var = "' OR 1'";

    $name = mysql_real_escape_string($bad_var);

    $bad_query = "SELECT * FROM customers WHERE username = '$name'";
    echo "Escaped Bad Injection: <br />" . $bad_query . "<br />";


    $qry = "'; DELETE FROM customers WHERE 1 or username = '";

    $qry_var = mysql_real_escape_string($qry);

    $query_result = "SELECT * FROM customers WHERE username = '$qry_val'";
    echo "Escaped Injection: <br />" . $query_result;





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here