0

I'm working with db connection, from what it looks like to me when I finish writing it on sublime there's no error. so, I decided to write localhost/*folder*/*filename*.php in my browser to check the connection and suddenly the browser display;

Notice: Undefined index: username in C:\xampp\htdocs\Login\login.php on line 4 Notice: Undefined index: pincode in C:\xampp\htdocs\Login\login.php on line 5 {"success":false}

<?php
    $con = mysqli_connect("localhost", "root", "", "test");

    $Username = $_POST["username"];
    $Pincode = $_POST["pincode"];

    $statement = mysqli_prepare($con, "SELECT * FROM users WHERE username = ? AND pincode = ?");
    mysqli_stmt_bind_param($statement, "ss", $Username, $Pincode);
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $id, $Username, $Pincode);

    $response = array();
    $response["success"] = false;  

    while(mysqli_stmt_fetch($statement)){
        $response["success"] = true;  
        $response["id"] = $id;
        $response["username"] = $Username;
        $response["pincode"] = $Pincode;
    }

    echo json_encode($response);
?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141

3 Answers3

1

Replace Line 4 and 5 by :

$Username = (isset($_POST["username"]))?$_POST["username"]:'';
$Pincode = (isset($_POST["pincode"]))?$_POST["pincode"]:'';
0
  • Provide validation to check if the username and pincode exist first.

e.g. replace lines 3 and 4 with this

if(isset($_POST['username']) )
{
     $Username = $_POST['username'];
}

if(isset($_POST['pincode']) )
{
     $Pincode = $_POST['pincode'];
}
  • and you need to make sure the page that calls this page, POST's the username and pincode.

e.g. in another file.

<form ....>
<input name="username" value="..." />
<input name="pincode" value="..." />
</form>
0

You want to check if Username and pincode were sent before querying the db. If they are not passed then your query doesn't have to be run.

if(isset($_POST['username']) && isset($_POST['pincode'])){
   $con = mysqli_connect("localhost", "root", "", "test");

   $Username = $_POST["username"];
   $Pincode = $_POST["pincode"];

   ... etc.
} else {
   echo "Username or pincode missing";
}
Kasia Gogolek
  • 3,374
  • 4
  • 33
  • 50