-2

I want to ask if I can prevent sql injection with this code?

<?php
$mysqli = new mysqli("localhost", "root", "", "lists");  
    if (isset($_POST['main'])) {
    if (isset($_POST['sub'])) {
    $main = $mysqli->real_escape_string($_POST["main"]);
    $sub = $mysqli->real_escape_string($_POST["sub"]);

    query . . . .

    }
    }
?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
user3097736
  • 284
  • 5
  • 23

1 Answers1

1

Duplicate of: How can I prevent SQL injection in PHP?

Use prepared statements and parameterized queries. You can do it like this:

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name=? and age=?');
$stmt->bind_param('si', $_POST['name'], $_POST['age']);
$stmt->execute();

The 'si' means string and integer, each letter to every param corresponding to every '?'. Further info can be found here: http://www.php.net/manual/en/mysqli-stmt.bind-param.php

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

Regards.

Community
  • 1
  • 1
João Pinho
  • 3,725
  • 1
  • 19
  • 29