-1

I am unable to pass proper data to MySQL I have no idea what is wrong done by me please help me out my code is as follow:

$con = mysqli_connect('localhost', 'root', '', 'database');
if($con) {
    echo "we are connected";
} else {
    die("connection failed");
}

if(isset($_POST['submit'])) {

    // echo "Yeah it works";
    $user = $_POST['username'];
    $pass = $_POST['password'];

    $query = "INSERT INTO users(username, password) VALUES ('$user', '$pass')";
    $result = mysqli_query($con, $query);

    if(!$result) {
        die("Query failed");
    }
}

When I run this code I'm getting 0 for username and 0 for password. whatever I type for username and password I get 0 in database. enter image description here

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Rahul Gurujala
  • 196
  • 2
  • 14

1 Answers1

2

Try this code, which also removes SQL injections.

$con = mysqli_connect('localhost', 'root', '', 'database');

if(! $con )
    die('Unable to connect');

foreach(array('submit', 'username', 'password') as $arg)
    if(! isset($_POST[$arg]) )
        die('Missing argument(s)');

unset($arg);
http_response_code(200);

$username = $con->real_escape_string($_POST['username']);
$password = $con->real_escape_string($_POST['password']);

$query = "INSERT INTO users (username, password) VALUES ('{$username}', '{$password}')";
if(! mysqli_query($con, $query))
    http_response_code(400);

If this code doesn't work, make sure that username and password from your table are varchar's not int's. (Because your script inserts a 0 value)

Jaquarh
  • 6,493
  • 7
  • 34
  • 86
Jakob
  • 1,858
  • 2
  • 15
  • 26