文件中有两个PHP块

时间:2013-11-09 14:04:52

标签: php html forms block

我在一个文件中有两个HTML表单和两个PHP块(index.php)。例如,我希望第二个PHP脚本属于第二个窗体。我不知道,怎么做。我写的动作属性是什么?

这是我的代码:

<form method="post" action="htmlspecialchars $_SERVER ["PHP_SELF"]">
<input type="text" name="name"> <br>
<input type="submit">
</form>

<form method="post" action="htmlspecialchars $_SERVER ["PHP_SELF"]">
<input type="text" name="age"> <br>
<input type="submit">
</form>

<?php
echo $_POST ["name"];
?>

<?php
echo $_POST ["age"]; 
?>

3 个答案:

答案 0 :(得分:0)

希望它可以帮到你,

第一种形式,

    <form method="post" action="<?php echo $_SERVER ["PHP_SELF"];?> ">
        <input type="text" name="name"> <br>
        <input type="submit" name='submit' >
    </form>

<?php

    if(isset($_POST['submit'])){
            echo $_POST ["name"];
    }
?>

第二种形式

    <form method="post" action="<?php echo $_SERVER ["PHP_SELF"];?>">
        <input type="text" name="age"> <br>
        <input type="submit" name='submitsecond' > // name submitsecond indicates as second form
    </form>

<?php

    if(isset($_POST['submitsecond'])){
            echo $_POST ["age"];
    }
?>  

答案 1 :(得分:0)

您可以使用隐藏的输入字段来区分两个脚本。你必须回显/打印脚本名称($_SERVER['PHP_SELF']),不需要htmlspecialchars ......

<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
    <input type="hidden" name="form" value="name_form" />
    <input type="text" name="name"> <br>
    <input type="submit">
</form>

<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
    <input type="hidden" name="form" value="age_form" />
    <input type="text" name="age"> <br>
    <input type="submit">
</form>

<?php if($_POST['form'] == 'name_form'): ?>
    The name form is submitted.<br>
    Name: <?php echo $_POST['name']; ?>
<?php endif; ?>

<?php if($_POST['form'] == 'age_form'): ?>
    The age form is submitted.<br>
    Age: <?php echo $_POST['age']; ?>
<?php endif; ?>

答案 2 :(得分:-1)

 <form method="post" action="<?php echo htmlspecialchars($_SERVER ["PHP_SELF"]); ?>">
<input type="text" name="name"> <br>
<input type="submit" name="name_sub">
</form>

    <?php
    if(isset($_POST ["name_sub"])) // check if name form is submit
    echo $_POST ["name"]; 
    ?>