I have a simple form.

<form action="" method="post">
            <label for="user">Name</label>
            <input type="text" name="user" id="user" />
            <label for="title">Title</label>
            <input type="text" name="title" id="title" />
            <textarea name="body" rows="20" cols="60"></textarea>
            <input type="submit" value="Add Post" />

I am trying to insert this to a table, which I am able to do. But before I actually insert I wanted to validate the form. Simple validation: whether field is null or not. I used isset() function:

if(isset($_POST['user'], $_POST['title'], $_POST['body'])){
    addPost(); // funtion that inserts record

I thought that isset() check for nulls, but when I submit an empty form, it still inserts to the table.

Can someone please explain this function to me, because from what I understand, isset() will return false when at least 1 of the parameters are null.


Recommended Answers

All 5 Replies

Member Avatar

you also need to check it for empty strings after isset.

if (isset($_POST['user'], $_POST['title'], $_POST['body'])
&&  ''==$_POST['user']
&&  ''==$_POST['title']
&&  ''==$_POST['body']
) {
    addPost(); // funtion that inserts record

you might also choose instead to use empty() instead of the ''== comparison if you want to eliminate leading and trailing spaces in with that check for an empty string. it does not check isset though. wish it did.

Yeah, its probably best to create your own function to check this, maybe check for special characters and whether or not a user has inputed some php code. Strip tags etc....

yeah the're right should check the string................it really returns true becasuse POST and GET returns empty string and empty string is not null.... thats y it returns true....

isset() returns TRUE if a value is NULL.
You can use below code for string validation


if($_POST['user']!="" && $_POST['title']!="" && $_POST['body']!="")

    echo "Insert";


 <form  action="test.php" method="post">

<input type="text" name="user" id="user" />

<input type="text" name="title" id="title" />
<textarea name="body" rows="20" cols="60">

issset() don't check for null. It just check the variable has already set or not. If the variable already defined or set, it return true, and return false otherwise. Your code will always work every time the form has submitted, because it just send empty value (it is not null) even if there is no value within the form. You should try like what @rajengg mentioned above.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.