-3

PHPについてはよくわからないので、データをtxtファイルに送信する簡単なフォームを作成しました。私の問題は、一部のフィールドが入力されていない場合にフォームの送信を停止する方法がわからないことです。誰かが私を正しい方向に向けることができますか?

また、塗りつぶされていない赤を作成し、フォームに正しく入力するようにユーザーに警告する単純なJavaScriptもありtextareasますが、値を空としてtxtファイルに送信するため、送信を許可したくありません。

<?php                       
    if(isset($_POST['button'])) {
        $myFile = 'demo.txt';
        $titel = $_POST['filmnamn'] . ";" ;
        $betyg = $_POST['betyg'] . ";" ;
        $link = $_POST['link'] . ";" ;
        $photo = $_POST['photo'] . ";" ;
        $desc = $_POST['description'] . ";" ;
        $data = "$titel$betyg$link$photo$desc";
        $fh = fopen($myFile, 'a');
        fwrite($fh, $data);

        fclose($fh);                        
}
?>
4

3 に答える 3

4

そもそもフォームの送信を停止するには、HTMLとJavascriptが必要です。したがって、基本的に、関数を送信ボタンにリンクすると、関数がtrueを返した場合にのみ送信されます。

<form action="..." method="post" onsubmit="return ValidatePage(this);">
    <script type="text/javascript">

    function ValidatePage(form) { // the form itself is passed into the form variable. You can choose not to use it if you want.
       // validating stuff.
    }

</script>

また、誰かがJavascriptに夢中になっている場合に備えて、サーバー側の検証が必要になります。

if ( !$title1) { echo "there has been an error" } // alternatively to the '!$title1' you can use empty($title1), which is what I use more often and may work better. Another possible alternative is to use a variable that you set to true if an error has occurred, that way the bulk of your code can be at the beginning.

else if... // repeat the if statement with else if for the remaining fields. 

else {...} // add the code to add to text file here.

より完全な例がここにあります:下にスクロールした場合はhttp://phpmaster.com/form-validation-with-php/ 。

また、PHPには、フォームの送信を最初から停止する方法がないことを知っておく必要があります。フォームが何も「実行」しないようにするだけです。

于 2013-03-20T14:53:08.427 に答える
2

あなたがやろうとしていることは、サーバー側の検証と呼ばれています。あなたがすべきことは、何よりも先に変数をテストすることです。これは、filemnamn変数とbetyg変数が空でない場合にのみファイルを書き込みます。

          <?php                     
                if(isset($_POST['button'])) {
                    if( $_POST['filmnamn'] != "" &&    $_POST['betyg'] != "") {
                    $myFile = 'demo.txt';
                    $titel = $_POST['filmnamn'] . ";" ;
                    $betyg = $_POST['betyg'] . ";" ;
                    $link = $_POST['link'] . ";" ;
                    $photo = $_POST['photo'] . ";" ;
                    $desc = $_POST['description'] . ";" ;
                    $data = "$titel$betyg$link$photo$desc";
                    $fh = fopen($myFile, 'a');
                    fwrite($fh, $data);

                    fclose($fh);   
                 }
                }
          ?>
于 2013-03-20T14:55:06.817 に答える
0
if ( !$title1 || !$betyg || !$link || !$photo || !$desc) {
//form + error message if blank
} else {
                        $fh = fopen($myFile, 'a');
                        fwrite($fh, $data);
                        fclose($fh);       
}

上記はすべてのフィールドのみを検証し、個々のフィールドは検証しません

于 2013-03-20T14:55:18.907 に答える