-2

I'm trying to put a login script together... but I'm having issues with the first bit.. I've included a database connection file.. now I'm trying to make sure the user does not leave the fields blank.. here is the code:

<?php 

// create database connection 

$db = include 'dbcon.php';

// executes code if and when form has been submitted 

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

    if(empty($_POST['username']) || empty($_POST['password'])) {
        echo 'Error!' ; }

}

?>

The problem I'm having is that it won't print out the echo messages.. why is it doing this?

Qirel
  • 25,449
  • 7
  • 45
  • 62
Sohail Arif
  • 86
  • 1
  • 10

3 Answers3

1

Its working for me: Make sure you have used the correct name for input fields.

if(isset($_POST['submit']))
{
  if(empty($_POST['username']) || empty($_POST['password'])) {
    echo 'Error!' ;}  } 



<form method="post" action="">
    <p>Username <input class="input-box" type="text" name="username"></p>
    <p>Password <input type="password" name="password" value=""></p>
    <p class="submit"><input class="input-box" type="submit" name="submit" value="Login"></p>
  </form>  
  • Nope... I placed that code in a separate php file and it still displays a blank screen when I submit the form! – Sohail Arif Oct 26 '15 at 12:07
  • 1
    @SohailArif - If it worked, then it should display a blank screen. It will only echo the *Error!* when the username or password fields are left blank. – Geoff Atkins Oct 26 '15 at 13:30
  • it should display "error" when there's nothing in the fields and the form is submitted.... if there is something in the field and its submitted.. then it should be blank... you are right. – Sohail Arif Oct 26 '15 at 13:45
0

@Sohail,

You can try using the 'required' keyword inside the input tags.

<input type="text" name="username" required>
<input type="password" name="pwd" required>

This would make sure the form will not be submitted unless User enters some value for the fields.

You can read more about the required attribute here.

Also, be aware that form can still be submitted if blank spaces are provided in the input fields.

Alternatively, you can do form validation before the form is submitted. Try this link. This should help you out.

0

I have fixed the error.. the problem was in the html code ... I changed it from this:

<input type="submit" value="login">

to this:

<input type="submit" name="submit" value="login">

Thanks for the suggestions guys!

Sohail Arif
  • 86
  • 1
  • 10
  • your question would have been solved within seconds probably, had you shown us your related form code. Your question was closed accordingly. – Funk Forty Niner Oct 26 '15 at 12:15
  • Apologies, I'm new to stackoverflow.. I tried pasting my html code in but it was giving me a code format error. – Sohail Arif Oct 26 '15 at 12:17