Problem with comments in form

I’ve created a form which has four fields, as shown in the image below :

Here is the code :

<?php //Get user inputs $username = $_POST['username']; $age = $_POST['age']; $education = $_POST['education']; $comments = $_POST['comments'];

//Creating a file
$filename = ‘C:\xampp\htdocs\Macro_Project_01\output\output2.txt’;
$file = fopen( $filename, “w+” );

if($_SERVER[‘REQUEST_METHOD’] == ‘POST’){
if($username && $age && $education && $comments = “”){
echo(“Fill out all the fields and return again.”);
} else {
fwrite( $file, "Your Username : " .$username. “\n” );
fwrite( $file, "\n Your Age : " .$age. “\n” );
fwrite( $file, "\n Your Education : " .$education. “\n” );
fwrite( $file, "\n Your Comments : " .$comments. “\n” );
fwrite( $file, “This documents is created by Macro Project By : Akhil Kokani\n” );
echo("Data written into file successfully. URL : " .$filename. “
”);
fclose( $file );
}
}
?>

When I execute the script
It executes the file properly, but only the problem is that even if I add comments, it is not writing comments in the output2.txt file
WHY?

You should put all those $_POST values inside if($_SERVER['REQUEST_METHOD'] == 'POST') because you will most likely get undefined index on when you try to access that file directly.

1 Like

This line

if($username && $age && $education && $comments = "")

is not doing what you want it to, I think.
You need to test each variable separately

if($username == "" && $age == "" && $education == "" && $comments == "")

although I think that should probably be not equal to - still need my first coffee of the day!

1 Like

I hear that :coffee:

Looks like a Logic error going by what the conditionals are testing for and the message.

 if($username && $age && $education && $comments = ""){
echo("Fill out all the fields and return again."); 

The if is testing if all of those are empty - but the message looks to be for an if any of those are empty.

That is, it doesn’t say “Fill out at least one field and try again.”

1 Like

Something else. You haven’t given us your form markup, but it looks like you are relying on placeholders to inform users what to enter. This is bad practice for 2 reasons. Firstly, it is not accessible - screenreaders will not read placeholders; secondly, the placeholders will not be displayed if someone is using auto-complete. Each form field needs to have a label tag.

1 Like

And this line

if($username && $age && $education && $comments = ""){

just sets the $comments field to be empty anyway, because of the missing = sign, and the assignment always evaluates to ‘true’ because it’s always able to execute it.

1 Like

You can also use AND and OR instead of && and || as it will reduce the confusion of which conditions are being used.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.