复选框表单验证并在PHP中提交表单本身

时间:2014-04-20 21:01:58

标签: php html

我编写的以下程序PHP要求用户选择他们熟悉的语言,并在同一页面中显示所选语言。如果用户没有选择任何语言,我可以显示错误消息。但我需要显示所选的复选框项目,即在同一页面本身中的语言。 示例:您认识的语言是英语,法语。 有人可以帮忙吗?

<?php
$languages_error = $languages_result = $languages_list = "";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if(empty($_POST["languages"])){
        $languages_error = "*Select the languages which you know";
    }
    else
    {
        $languages_result = "Languages selected are";       
    }       
}
?>

<!DOCTYPE html>
<html>
<head>

<title>Check Box Page</title>
</head>
<body>
<div id="contact">
    <h1>What languages do you know?</h1><br>
    <form action="checkbox.php" method="post">
    <fieldset>      
        <input type="checkbox" name="languages[]" id="languages" value="English"><label for = "gender">English</label></br>
        <input type="checkbox" name="languages[]" id="languages" value="Spanish"><label for = "gender">Spanish</label></br>
        <input type="checkbox" name="languages[]" id="languages" value="French"><label for = "gender">French</label></br>
        <input type="checkbox" name="languages[]" id="languages" value="Germany"><label for = "gender">Germany</label></br>
        <input type="checkbox" name="languages[]" id="languages" value="Chinese"><label for = "gender">Chinese</label></br>     
        <?php echo $languages_error, $languages_result ?></br>      
        <input type="submit" value="submit">
    </fieldset> 
    </form>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

将提交所选语言(复选框),并以PHP Array提供。

要访问它们,您可以循环访问它们,并按原样回显:

$languages_result = $_POST['languages'];

foreach ($languages_result as $language) {
    echo $language . '<br />';
}

// Result is:
// English
// Telegu
// Kanada

您还可以使用分隔符在String中组合数组中的多个元素:

$languages_result = implode(', ', $_POST['languages']);

echo $languages_result;

// Result is:
// English, Telegu, Kanada