0

I'm struggling with my code because it's a little bit complex than having a form save its data to a text file. I wanted the form to show conditional messages like if an empty form is submitted a "please enter comment" will show, if finished is entered it will show that the data is accepted and a "congratulations" will appear. If it is any other data, it will simply say that data is received and "thank you for the comment" will appear. I was able to do this but for some reason I can't make the entered data from the php file save to the text file. Here is my code:

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset ="UTF-8">
        <title>mission_2-02</title>
    </head>
    <body>
        <form action="" method="post">
            <input type="text" name="comment" placeholder="comment">
            <input type="submit" name="submit">
        </form>

        <?php
            $str = $comment . PHP_EOL;
            $filename="mission_2-02.txt";
            $fp = fopen($filename,"w");

            $comment = $_POST ["comment"];
            if ($comment==""){echo "";}
            else echo $comment . "is accepted <br>";


            if (empty ($comment)) {echo"please enter comment";}
            elseif ($comment=="finished"){echo "congratulations";}
            elseif (!empty($comment)){echo "thank you for the comment";}
            else{fwrite($fp, $str );echo $str ;fclose($fp);}
            
            
            if (file_exists($filename)){
                $lines = file($filename,FILE_IGNORE_NEW_LINES);
                foreach ($lines as $line){
                    echo $line . "<br>";
                }  
            }
        ?>
    </body>
</html>
3
  • 1
    your HTML markup is invalid. The closing </head> must come before the opening <body> tag and there should be a space between meta and charset in <metacharset ="UTF-8"> Commented Aug 11, 2020 at 13:26
  • 1
    It looks like the question has nothing to do with MySql Commented Aug 11, 2020 at 13:28
  • 1
    You are assigning a variable before it has been defined - $str = $comment . PHP_EOL; ~ at that stage it has not been created Commented Aug 11, 2020 at 13:31

2 Answers 2

1

A variation on a theme perhaps...

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset='UTF-8' />
        <title>mission_2-02</title>
    </head>
    <body>
        <form method='post'>
            <input type='text' name='comment' placeholder='comment' />
            <input type='submit' />
        </form>

        <?php
            
            $filename='mission_2-02.txt';
            
            if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST["comment"] ) ){
                
                $output=array();
                $errors=array();
                
                $comment=filter_input( INPUT_POST, 'comment', FILTER_SANITIZE_STRING );
                
                
                if( !empty( $comment ) )$output[]=sprintf('Thankyou - your comment "%s" was accepted!', $comment );
                else $errors[]='Please enter a comment!';
                
                if( strtolower( trim( $comment ) )==='finished' )$errors[]='Congratulations';
                
                if( !empty( $errors ) )printf('<pre>%s</pre>',implode( PHP_EOL, $errors ));
                else{
                    file_put_contents( $filename, $comment . PHP_EOL, FILE_APPEND );
                    printf('<pre>%s</pre>',implode( PHP_EOL, $output ) );
                }
            }
            
            
            if( file_exists( $filename ) ){
                foreach( file( $filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ) as $line )printf('%s<br />',$line);
            }

            clearstatcache();
        ?>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

0

Using valid tools for working with PHP and valid formatting for clarity, would help you faster.

  1. You can not assign variable before it has been defined (as ProfessorAbronsius pointed)
  2. You trying to write the file content in the else clause which is not reached

compare:

<?php
$filename = "mission_2-02.txt";
$fp = fopen($filename, "w");

$comment = $_POST ["comment"];
$str = $comment . PHP_EOL;
if ($comment == "") {
    echo "";
} else {
    echo $comment . "is accepted <br>";
}


if (empty($comment)) {
    echo "please enter comment";
} elseif ($comment == "finished") {
    echo "congratulations";
} elseif (!empty($comment)) {
    fwrite($fp, $str);
    echo $str;
    fclose($fp);
    echo "thank you for the comment";
} else { // this is unreachable
    fwrite($fp, $str);
    echo $str;
    fclose($fp);
}

echo '<br>Output<br>';
if (file_exists($filename)) {
    $lines = file($filename, FILE_IGNORE_NEW_LINES);
    foreach ($lines as $line) {
        echo $line . "<br>";
    }
}
?>

BTW note that this way you override the whole file each time, except appending new values.

Tip: although using if/else statements without brackets is valid in PHP it's not safe consider code below:

// not safe approach, altough still valid, 
// in this case last echo is OUT of the else statement!
if (1 == 1)
    echo 'equal';
else
    echo 'not equal';
    echo 'something else';

// safe approach
if (1 == 1) {
    echo 'equal';
}
else {
    echo 'not equal';
    echo 'something else';
}

// short valid approach
echo (1 == 1) ? 'equal' : 'not equal';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.