【问题标题】:Form Processing php表单处理 php
【发布时间】:2021-12-05 03:46:45
【问题描述】:

我是新来的,所以如果我误解了如何在这里提交问题,请指出正确的方向。

1. 我收到警告错误,指出我有“未定义的数组键”。我在提交表格之前和之后得到这个。我已经在顶部定义了数组,所以我不确定为什么它们是未定义的。

2.如果我输入了错误的电话号码格式,我的错误捕获将不起作用。我最初收到错误消息,说明以正确的格式输入,但如果我以正确的格式输入信息并提交,我仍然会收到错误消息,并且电话号码会重置为最初的状态。我知道它是从 $_GET 中提取的,但不知道为什么当它再次提交时它没有更新 $_GET 以正确填充它。


<?php

function validate_field_contents($content, $title, $type, $message, ) {
    if($type == 'text') {
        $string_exp = "/^[A-Za-z0-9._%-]/";
        if(!preg_match($string_exp, $content)) {
            $message .= '<li>Please enter a valid ' . strtolower($title) . '.</li>';
        }
    } 
    elseif($type == 'email') {
        $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
        if(!preg_match($email_exp, $content)) {
            $message .= '<li>Please enter a valid ' . strtolower($title) . '.</li>';
        }
    }
    elseif($type == 'phone'){
        $num_exp = "/^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$/";
         if(!preg_match($num_exp,$content)) {
             {$message .= '<li>Please enter a valid ' . strtolower($title) . ' in the following format (xxx)xxx-xxxx.</li>';}
        }
    }
    elseif($type == 'zip'){
        $num_exp = "/^[0-9]{5}$/";
         if(!preg_match($num_exp,$content)) {
             {$message .= '<li>Please enter a valid ' . strtolower($title) . ' with 5 numbers only.</li>';}
        }
    }
    elseif(empty($_POST['band'])){
            {$message .= '<li>Please select a ' . strtolower($title) . '.</li>';}
    }
    elseif(empty($type == 'color')){
         $message .= '<li>Please select a ' . strtolower($title) . '.</li>';
        }
    elseif(empty($type == 'size')){
         $message .= '<li>Please select a ' . strtolower($title) . '.</li>';
        }
    elseif(empty($type == 'style')){
         $message .= '<li>Please select a ' . strtolower($title) . '.</li>';
        }
    return $message;
}
?>

【问题讨论】:

    标签: php forms validation error-handling


    【解决方案1】:

    好的,这里有几件事:

    • 您不需要顶部的变量分配。这在 C 和其他语言中非常重要,但 PHP 不需要。

    • 您的if(isset($_GET['firstName'])) $firstName = $_GET['firstName']; 语句使用$_GET 而您的&lt;form&gt; 标签使用$_POST - 这是您的主要问题

    • 我建议使用变量数组,如下所示:

       $address_vars = array(
        array(
           'element_name' => 'firstName',
           'title' => 'First Name',
           'validation' => 'text',
        ),
        array(
           'element_name' => 'lastName',
           'title' => 'Last Name',
           'validation' => 'text',
        ),
      );
      

    然后您可以像这样以编程方式输出字段:

    foreach($address_vars as $cur_address_field) {
        ?>
            <label><?php echo $cur_address_field['title']; ?>: <input type = "text" value="<?php echo (isset($_POST[$cur_address_field['element_name']]) ? $_POST[$cur_address_field['element_name']] : ''); ?>" id = "<?php echo $cur_address_field['element_name']; ?>" placeholder = "<?php echo $cur_address_field['title']; ?>" name ="<?php echo $cur_address_field['element_name']; ?>"></label>
        <?php
    }
    

    这不仅大大清理了代码,而且还使更改/更新甚至添加到字段变得更加容易(并且更安全)。

    然后,要验证字段,您可以使用我设置为开关的validation 数组键来遍历所有字段。像这样的:

    foreach($address_vars as $validate_field) {
        if($validate_field['validation'] == 'text') {
            // this is a text-based field, so we check it against the text-only regex
            $string_exp = "/^[A-Za-z .'-]+$/";
            if(!preg_match($string_exp, $_POST[$validate_field['element_name']])) {
                $message .= '<li>Please enter a ' . strtolower($validate_field['title']) . ' containing letters and spaces only.</li>';
            }
        } elseif($validate_field['validation'] == 'email') {
            $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
            if(!preg_match($email_exp, $_POST[$validate_field['element_name']])) {
                $message .= '<li>Please enter a valid ' . strtolower($validate_field['title']) . '.</li>';
            }
        }
    }
    
    • 您没有正确连接您的产品字段。用户提交的值无法在此处“粘贴”,因此该字段的值完全丢失了。首先,我们可以将这些都放在一个数组中,类似于我们对地址字段所做的:

      $product_vars = 数组( 大批( 'element_name' => '乐队', '标题' => '乐队', '选项' => $bands, '占位符' => '选择一个', ), 大批( '元素名称' => '颜色', '标题' => '颜色', '选项' => $颜色, '占位符' => '选择一个', ), );

    那么我们可以使用以下形式:

    foreach($product_vars as $cur_product) {
        ?>
                <label><?php echo $cur_product['title']; ?>: </label>
                    <select name="<?php echo $cur_product['element_name']; ?>" size="1">
                        <option><?php echo $cur_product['placeholder']; ?></option>
                        <?php
                            foreach($cur_product['options'] as $cur_option)
                            {
                                echo "<option value = '".$cur_option."' ".(isset($_POST[$cur_product['element_name']]) && $_POST[$cur_product['element_name']] == $cur_option ? "selected='selected'" : "")."> $cur_option </option>";
                            }
                        ?>
                    </select>
        <?php
    }
    

    希望这会有所帮助!

    **因共享新代码而编辑**

    这里又发生了一些事情。主要项目是:$product_vars foreach 位于 &lt;form&gt; 标记之外,&lt;form&gt; 标记未设置为使用 $_POST,尽管其余代码均以这种方式设置,并且未添加任何验证类型。我已经粘贴了我拥有的完整代码,这对我有用。

    <?php
            //arrays
            $bands = array ("ACDC", "Journey", "Modest Mouse", "Band of Horses", "Vampire Weekend", "Of Monsters and Men", "Broken Bells", "Phoenix", "Fleetwood Mac", "AJR",);
            $colors = array ("Black", "Navy", "Red", "Orange", "Pink", "Yellow", "Green", "Gray", "White", "Purple",);
            $sizes = array ("X-Small", "Small", "Medium", "Large", "X-Large", "XX-Large", "XXX-Large",);
            $styles = array ("Tank Top", "T-Shirt", "Long Sleeve", "Hoodie", "Sweatshirt", "Jacket",);
            
            $product_vars = array(
            array( 'element_name' => 'band', 'title' => 'Band', 'options' => $bands, 'placeholder' => 'Choose One', ), 
            array( 'element_name' => 'color', 'title' => 'Color', 'options' => $colors, 'placeholder' => 'Choose One', ), 
            array( 'element_name' => 'size', 'title' => 'Size', 'options' => $sizes, 'placeholder' => 'Choose One', ), 
            array( 'element_name' => 'style', 'title' => 'Style', 'options' => $styles, 'placeholder' => 'Choose One', ), 
            );
        
            $address_vars = array(
            array(  'element_name' => 'firstName', 'title' => 'First Name', 'validation' => 'text',),
            array(  'element_name' => 'lastName',   'title' => 'Last Name', 'validation' => 'text',),
            array(  'element_name' => 'email', 'title' => 'Email Address', 'validation' => 'email',),
            array(  'element_name' => 'phone', 'title' => 'Phone Number', 'validation' => 'phone',),
            array(  'element_name' => 'address', 'title' => 'Address', 'validation' => 'address',),
            array(  'element_name' => 'city', 'title' => 'City', 'validation' => 'text',),
            array(  'element_name' => 'state', 'title' => 'State', 'validation' => 'text',),
            array(  'element_name' => 'zip', 'title' => 'Zip Code', 'validation' => 'zip',),
            );
        
            ?>
            <form action="" method="post">
            <?php
            foreach($product_vars as $cur_product) {
            ?>
                    <label><?php echo $cur_product['title']; ?>: </label>
                        <select name="<?php echo $cur_product['element_name']; ?>" size="1">
                            <option><?php echo $cur_product['placeholder']; ?></option>
                            <?php
                                foreach($cur_product['options'] as $cur_option)
                                {
                                    echo "<option value = '".$cur_option."' ".(isset($_POST[$cur_product['element_name']]) && $_POST[$cur_product['element_name']] == $cur_option ? "selected='selected'" : "")."> $cur_option </option>";
                                }
                            ?>
                        </select>
            <?php
            }
            foreach($address_vars as $cur_address_field) {
            ?>
        
                <label><?php echo $cur_address_field['title']; ?>: 
                    <input 
                    type = "text" 
                    value="<?php echo (isset($_POST[$cur_address_field['element_name']]) ? $_POST[$cur_address_field['element_name']] : ''); ?>" 
                    id = "<?php echo $cur_address_field['element_name']; ?>" 
                    placeholder = "<?php echo $cur_address_field['title']; ?>" 
                    name ="<?php echo $cur_address_field['element_name']; ?>">  
                </label>
                <?php } ?>
                    <input type="reset" class="buttons">
                    <input type="submit" class="buttons">
                </form>
            <?php
    
    
            foreach($address_vars as $validate_field) {
                $message = validate_field_contents($_POST[$validate_field['element_name']], $validate_field['title'], $validate_field['validation'], $message);
            }
            ?>
        
        
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <title>T-Shirt Form</title>
                <link type="text/css" rel="stylesheet" href="css/style-prod.css">
                <script src="..js/script.js" defer></script>
            </head>
            <body>          
        
                <?php
                if($message) {
                    echo '<p>'.$message.'</p>';
                } else {
                ?>
    
                <!--display processed information here-->
                <h3 class="subheaderone">Thank you for your order!</h3><br>
                <h3 class = "subheadertwo">Product:</h3>
                <div class = "output">
                
                    <h3 class = "subheadertwo">Shipping & Contact Information:</h3>
                    <?php foreach($address_vars as $cur_address) {
                        echo '<p>' . $cur_address['title'] . ': ' . (isset($_POST[$cur_address['element_name']]) ? $_POST[$cur_address['element_name']] : '') . '</p>';
                    } ?>
                </div>
                <div class="another"> 
                    <nav><a href="./products.php"> Submit Another Form</a></nav> 
                </div>
                <?php } ?>
            </body>
        </html>
    
    
    <?php
    
    function validate_field_contents($content, $title, $type, $message) {
        if($type == 'text') {
            // this is a text-based field, so we check it against the text-only regex
            $string_exp = "/^[A-Za-z .'-]+$/";
            if(!preg_match($string_exp, $content)) {
                $message .= '<li>Please enter a valid ' . strtolower($title) . ' containing letters and spaces only.</li>';
            }
        } elseif($type == 'email') {
            $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
            if(!preg_match($email_exp, $content)) {
                $message .= '<li>Please enter a valid ' . strtolower($title) . '.</li>';
            }
        }
        return $message;
    }
    

    【讨论】:

    • 感谢您帮助清理我的代码。这很有帮助。
    • 我按照您的建议进行了编辑,包括提交按钮和清除按钮以及地址和下拉列表所需的其他字段/变量。我也将 ifset 更改为 $_POST 。但是,它仍然没有保存提交的信息(我看到 $_GET var_dump 数组中的地址信息,但没有看到下拉信息),如果有错误则填充错误,或者显示要提交的表单或感谢消息没有表格显示。我仍然收到警告:所有地址变量的未定义数组键“______”消息。
    • 你能用更新的代码编辑你的问题吗?另外,看看当它说“未定义的数组键”时引用了哪些行号
    • 我将代码更新为我所拥有的。我尝试添加我在顶部的变量,解决了一些问题,也解决了一些问题。相反,它也是同时填充的,所以我在提交的顶部添加了一条评论,如果这有帮助,我会尝试实现所需的输出。其他错误来自我提交时的 HTML 输出。我在想也许我需要一个“if(empty($_POST['submit-button]))”语句来表示 if empty 和 if !empty 来填充表单或填充谢谢。我试图将它输入到编码中,但我也无法让它正常工作。
    • @monkey84 我已经用我最终得到的代码编辑了我的答案,这对我有用。您需要在 validate_field_contents 函数中添加更多验证规则等。
    猜你喜欢
    • 1970-01-01
    • 2015-07-09
    • 2015-05-17
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多