1

I am learning php mysql but I am facing this problem. I cannot insert login information to my database table. My database name is loginapp and table name is users. Please review the code those i created for ----

<?php 
if(isset($_POST['submit'])){
   $username = $_POST['username'];
   $password = $_POST['password'];
    $connection = mysqli_connect('localhost', 'root', '','loginapp');
    if(!$connection){
    die("Database connection failed");
    }
    $query = "INSERT INTO users(username,password)";
    $query .= "VALUES ('$username', '$password')";
    $result = mysqli_query($connection, $query);
    if(!$result){
    die('query is faild' . mysqli_connect_error());
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login </title>
    <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

</head>
<body>

    <div class="container">
        <div class="col-xs-6">
             <form action="login.php" method="post">
                 <div class="form-group">
                    <label for="username">Username</label>
                     <input type="text"  name="username"class="form-control">
                 </div>
                  <div class="form-group">
                    <label for="password">Password</label>
                     <input type="password" name="password" class="form-control">
                 </div>
                 <input class="btn btn-primary" type="submit" name="submit" value="Submit">
             </form>
        </div>
    </div>
</body>
</html>
Ijas Ahamed N
  • 5,632
  • 5
  • 31
  • 53
Uzzal Chandra Dey
  • 91
  • 1
  • 2
  • 13

2 Answers2

5

You need space before your values

 $query = "INSERT INTO users(username,password)";

 $query .= " VALUES ('$username', '$password')";
            ^

Your code is open for sql injection , check below link to prevent it

How can I prevent SQL injection in PHP?

To check error in your query use

printf("Errormessage: %s\n", $mysqli->error);

http://php.net/manual/en/mysqli.error.php

TO check error in you connection with database use

if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

http://php.net/manual/en/mysqli.error.php

Don't store plain password into database use

http://php.net/manual/en/faq.passwords.php

http://php.net/manual/en/function.password-hash.php

Community
  • 1
  • 1
Saty
  • 22,443
  • 7
  • 33
  • 51
2

Try this

$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);

$query = "INSERT INTO users(username,password)";
$query .= " VALUES ('$username', '$password')";

Also, checkout your table and column name is correctly spelled.

Ijas Ahamed N
  • 5,632
  • 5
  • 31
  • 53