-2

I did not explain my problem in the title very well so let me give it another try, this is my register form (I want it to keep very simple and also in MySQLi not PDO or else).

<?php

require('library/sql/db.php');

if (isset($_POST['submit'])) {
    $username = mysqli_real_escape_string($db, $_POST['username']);
    $password = mysqli_real_escape_string($db, $_POST['password']);
    $h_password = password_hash($password, PASSWORD_DEFAULT);

    if (mysqli_query($db, 'INSERT INTO users (username, password) VALUES ( "$username","$h_password")')) {
        echo 'Registered';
    } else {
        echo 'Error';
    }
}

now the database,

This is what values the php code inserts in the sql

what's the way of fixing this ? I've tried anything I could find online. Thanks.

EDIT: Oh and also I tried swapping the "" to '' like this:

<?php
require('library/sql/db.php');

if(isset($_POST['submit']))
{
    $username = mysqli_real_escape_string($db, $_POST['username']);
    $password = mysqli_real_escape_string($db, $_POST['password']); 
    $h_password = password_hash($password, PASSWORD_DEFAULT);

    if(mysqli_query($db, "INSERT INTO users (username, password) VALUES ( '$username', '$h_password')")) 
    {
        echo 'Registered';
    }else{
        echo 'Error';
    }
}
ItzBlazik
  • 7
  • 6
  • Use prepared statements with bound parameters. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Apr 04 '18 at 15:05

1 Answers1

1

This is because single quote ' strings do not escape php variables. So, change it to this:

if(mysqli_query($db, "INSERT INTO users (username, password) VALUES ( '{$username}','{$h_password}')")) 

Note: Please use prepared statements Read More

mega6382
  • 9,211
  • 17
  • 48
  • 69