【发布时间】:2021-07-15 16:58:42
【问题描述】:
只使用核心 PHP 而没有其他,比如 JavaScript 或客户端编程,我需要 PHP 来检查表单的必填字段是否已填写,如果未填写则显示错误消息。我需要检查使用过程式编程,因为我还没有进入 OOP 并且不理解它。
HTML 表单
<html>
<head>
<title>
Searchengine Result Page
</title>
</head>
<body>
<form method = 'POST' action = "">
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<label for='url'>url</label>
<input type='url' name='url' id='url' required>
<br>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' required>
<br>
<label for='description'>description</label>
<input type='text' name='description' id='description' required>
<br>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' required>
<br>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' required>
<br>
<button type='submit'>Search!</button>
</form>
</body>
</html>
Php 表单验证器
<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels_count = count($required_labels);
for($i=0; $i!=$required_labels_count; $i++)
{
if(!ISSET(in_array(($_POST['$required_labels[$i]']),$required_labels))) //Incomplete line as I don't know how to complete the code here.
{
echo 'You must fill-in the field' .'Missed field\'s label goes here'; //How to echo the missed field's label here ?
}
}
?>
我知道我需要检查关联的数组值,因为这样会更容易且代码更少,但我不知道该怎么做。 注意我的错误回声。它不完整,因为我不知道如何编写代码的平静。 您将如何使用程序样式检查尽可能短的代码? 还有什么我需要知道的吗?
注意:我不想手动输入每个$_POST[] 来检查是否填写了所需的内容。我需要 PHP 循环遍历 $required_labels[] 数组并检查。或者,如果您知道任何更短的不循环检查方法,那么我想知道。
【问题讨论】:
-
给定的代码有什么不工作的地方吗?您尝试过什么来解决问题?