Reputation: 201
I have this code where i validate each field to be not empty and the problem is that when every field is filled I have to press submit twice in order for the form to be submitted.
<table>
<form method ="post" <?php
if(!empty($_POST['Firstname']) &&
!empty($_POST['Lastname']) &&
!empty($_POST['Email']) &&
!empty($_POST['Comments'])){
echo 'action="messagesent.php"';}
else if(isset($_POST['Firstname']) ||
isset($_POST['Lastname']) ||
isset($_POST['Email']) ||
isset($_POST['Comments'])) {
echo 'action="contact.php"';}?> >
<tr>
<td><label>Firstname:</td><td><input name ="Firstname" type ="text" size ="30" <?php if(!empty($_POST['Firstname'])){$Firstname=$_POST['Firstname'];echo "value=$Firstname";} ?> /></td><td><?php if(empty($_POST['Firstname'])){echo "<font color='blue'>*</font>";}?></td>
</tr>
<tr>
<td><label>Lastname:</td><td><input name="Lastname" type ="text" size ="30" <?php if(!empty($_POST['Lastname'])){$Lastname = $_POST['Lastname'];echo "value=$Lastname";}?> /></td><td><?php if(empty($_POST['Lastname'])){echo "<font color='blue'>*</font>";}?></td>
</tr>
<tr>
<td><label>E-mail:</td><td><input name="Email" type ="text" size ="30" <?php if(!empty($_POST['Email'])){$Email = $_POST['Email'];echo "value=$Email";}?> /></td><td><?php if(empty($_POST['Email'])){echo "<font color='blue'>*</font>";}?> </td>
</tr>
<tr>
<th colspan="2"><label>Your Message</th>
</tr>
<tr>
<td colspan="2"><textarea name= "Comments" rows="10" cols="34"><?php $Comments=$_POST['Comments'];if(!empty($_POST['Comments'])){echo "$Comments";} ?> </textarea></td><td><?php if(empty($_POST['Comments'])){echo "<font color='blue'>*</font>";}?> </td>
</tr>
<tr>
<td><input type="submit" value = "SUBMIT"/> </td>
</tr>
</form>
</table>
Upvotes: 0
Views: 1270
Reputation: 4868
It looks like you're expecting PHP to check whether the fields on the page are filled in. That's not how PHP works. It evaluates once, when the page is first rendered, and then never does anything again until the page is loaded again. PHP's $_POST
array doesn't refer to the input fields on the page; it refers to the values that the page received from the form when it was loaded. So what's happening is;
$_POST
is empty because no form was submitted. ACTION
to send you back to the same page.$_POST
has values in it because you just submitted the form. $_POST
and sets ACTION
to send you to the next page. If you want to check the form to see if the fields are filled in before the form is submitted, you can't use PHP. You'll need to use some javascript. Here's a quick tutorial, where the first example addresses what you're looking for.
Upvotes: 3