0

Is the method I use to insert data using MySQLi right? It works but is it safe enough?

    $login = stripslashes($login);
    $login = htmlspecialchars($login);
    $password = stripslashes($password);
    $password = htmlspecialchars($password);

    $login = trim($login);
    $password = trim($password);


 $result2=mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
  • 2
    Sanitizing input is a good step, using prepared statements it "safer": http://php.net/manual/en/mysqli.quickstart.prepared-statements.php – David Jan 31 '15 at 10:20
  • 2
    Use parameterized statements as provided by prepared statements. Then the library cares about proper data handling. – Gumbo Jan 31 '15 at 10:20
  • 3
    `stripslashes` and `htmlspecialchars` are not designed to prevent sql injection. `htmlspecialchars` is designed to make a string safe when it's returned to a browser, and you should only use that when a string will be returned to the browser. – Arjan Jan 31 '15 at 10:51
  • Duplicate: https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement – Dharman Nov 08 '19 at 21:44

3 Answers3

5

Whenever you interact with a database inside php you need to keep in mind a checklist :

  1. Set up the connection correctly, for example, make sure that when using pdo, set the error mode to exception and tell it not to emulate prepared statements. Use the following code to set the connection attributes :

    $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
  2. Use prepared statements and parameterized queries when fetching data.

Using mysqli:

    $stment = $dbConnection->prepare('SELECT * FROM users WHERE name = ?');
    $stment->bind_param('s', $name);

    $stment->execute();

    $result = $stment->get_result();
    while ($row = $result->fetch_assoc()) {
        // do something with $row
    }

Using PDO:

    $stment = $pdo->prepare('SELECT * FROM users WHERE name = :name');

    $stment->execute(array('name' => $name));

    foreach ($stment as $row) {
        // do something with $row
    }

The idea behind prepared queries is very simple - the query and the data are sent to the SQL server separately. When we send a database query along with the data, the data can be used to execute a potentially malicious query. For more info, refer this answer.

If you want to dynamically add identifiers and syntax keywords use whitelisting. It basically involves checking if the user input is an expected one, like this :

$orders  = array("name","price","qty"); //field names
$key     = array_search($_GET['sort'],$orders)); // see if we have such a name
$orderby = $orders[$key]; //if not, first one will be set automatically. smart enuf :)
$query   = "SELECT * FROM `table` ORDER BY $orderby"; //value is safe
  1. Sanitize input from the user before inserting/searching the database using functions like mysqli_real_escape_string, if you are not using prepared statements for some reason.
  2. Make sure you handle exceptions and errors well.
Community
  • 1
  • 1
bluefog
  • 1,894
  • 24
  • 28
0

Use PDO. Considered more secure than the outdated MySqli.

Whirl Mind
  • 884
  • 1
  • 9
  • 18
  • How is PDO more secure than MySQLi? – Gumbo Jan 31 '15 at 10:21
  • Well, that would be a lengthy discussion, and bring subjectivity to the scope of this question, I guess. See the links given by David in the comments to the question. – Whirl Mind Jan 31 '15 at 10:34
  • @WhirlMind The linked page does not say PDO is safer than MySQLi. – Gumbo Jan 31 '15 at 10:36
  • Mysqli is not outdated. Mysql, without the `i`, is. That is, all `mysql_` functions are deprecated. – Arjan Jan 31 '15 at 10:42
  • @Gumbo : Here, then. http://stackoverflow.com/questions/13569/mysqli-or-pdo-what-are-the-pros-and-cons – Whirl Mind Jan 31 '15 at 10:43
  • @WhirlMind First of all, mysqli isn't outdated, you are referring to the mysql API. Secondly, PDO is not more secure than mysqli either, David's comment is referring to prepared statements which mysqli supports. – EternalHour Jan 31 '15 at 10:43
  • @WhirlMind Still doesn’t say anything about PDO being more secure than MySQLi. Both PDO and MySQLi support prepared statements. – Gumbo Jan 31 '15 at 10:46
-3

You also can use following function for the same thing. You can prepare your final string which is directly being used in database query with the following function. This function will take care almost all the things which prevent sql injection and clean the harmful or unwanted content from your inputs.

function cleanInputs($data) {
    $clean_input = array();
    if (is_array($data)) {
        foreach($data as $k = > $v) {
            $clean_input[$k] = cleanInputs($v);
        }
    } else {
        if (get_magic_quotes_gpc()) {
            $data = trim(stripslashes($data));
        }
        $data = strip_tags($data);
        $clean_input = trim($data);
    }
    return $clean_input;
}

Things are depends on the requirement you can even modify the definition or logic accordingly.

Vikas Chaudhary
  • 728
  • 1
  • 5
  • 12
  • How exactly does this prevent SQL injections? – Gumbo Jan 31 '15 at 10:47
  • Firstly, this function does **not** make strings safe for use in queries. Secondly, it will remove parts of the string if the string contains a `<` sign, which gives very unexpected results. – Arjan Jan 31 '15 at 10:48
  • if you read the comment properly, i mentioned that according to your logic you can modify the code. – Vikas Chaudhary Jan 31 '15 at 11:12