Josel Parayno Josel Parayno - 24 days ago 10
PHP Question

php mysql forms validation

i already got message in my browser


Notice: Undefined variable: password in C:\xampp\htdocs\udemy\mysql\login.php on line 8 pls insert username and password


even i haven't submitted the form.

One more question how can i validate if the username and the password are submit with text.

<?php

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

if($username && $password){
echo $username;

echo $password;
}else{
echo "pls insert username and password";
}


?>



<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"
>
</head>
<body>
<div class="container">

<div class="col-sm-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="username">Password</label>
<input type="password" name="password"
class="form-control">
</div>

<div class="form-group">
<input type="submit" name="submit"
class="btn btn-primary">
</div>

</form>
</div>

</div>
</body>
</html>

Answer Source

Declare $username=$password='' before if(isset($_POST['submit']))

Maybe this could help you. Do modify in this code , but from this code you will get your error answer and also validation for you `

 $username=$password=''
 $valid=true;


if ($_SERVER["REQUEST_METHOD"] == "POST") {

if (empty($_POST["username"])) {

        $valid=false; 
      } 
      else {
        $username = test_input($_POST["username"]);

        if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
          echo 'User name only suppost space and letter';
          $valid=false;
        }
      }



       if (empty($_POST["password"])) {
        echo 'password can't be empty;
        $valid=false;
      } else {
        $password = test_input($_POST["password"]);

      }

     if($valid)

        {

            include('db_connect.php');

            $sql = "INSERT INTO tbl_user (id,username,password) VALUES 
 ('','$username',$password')";



            $conn->close();


        }           

 }



function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

?>`