我对PHP知之甚少,并制作了一个将数据发送到txt文件的简单表单。我的问题是,如果有些字段没有填写,我无法弄清楚如何停止提交表单。有人能指出我正确的方向吗?
我还有一个简单的javascript,可以使未填充的textareas
变为红色并提醒用户正确填写表单,但我不想允许提交,因为它仍然将值作为空值发送到txt -file。
<?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);
}
?>
答案 0 :(得分: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中没有办法阻止表单首先提交,你所能做的就是让表单不会这样做#34;做到&#34;任何东西。
答案 1 :(得分: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);
}
}
?>
答案 2 :(得分:0)
if ( !$title1 || !$betyg || !$link || !$photo || !$desc) {
//form + error message if blank
} else {
$fh = fopen($myFile, 'a');
fwrite($fh, $data);
fclose($fh);
}
以上只会验证所有字段,而不是单个