首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >表单处理php

表单处理php
EN

Stack Overflow用户
提问于 2021-10-18 02:21:14
回答 1查看 153关注 0票数 1

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

1.我收到警告错误,说明我有“未定义的数组键”。我在递交表格之前和之后都会收到这份表格。我已经在顶部定义了数组,所以我不知道为什么没有定义它们。

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

代码语言:javascript
复制
<?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;
}
?>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-18 17:21:05

好吧,这里有几件事:

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

  • 您的if(isset($_GET['firstName'])) $firstName = $_GET['firstName'];语句使用$_GET,而<form>标记使用$_POST --这是您的主要问题--

  • I建议使用一个变量数组,如下所示:

$address_vars =数组(数组(“element_name‘=> 'First Name”,'title’=>‘Name','validation’=> 'text',),数组( 'element_name‘=> 'lastName','title’=>‘lastName’,);

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

代码语言:javascript
复制
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数组键来遍历所有字段。就像这样:

代码语言:javascript
复制
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>';
        }
    }
}

  • 您没有正确地连接产品字段。用户提交的值无法在这里“粘贴”,因此字段的值就会丢失。首先,我们可以将所有这些都放在一个数组中,类似于我们对address字段所做的操作:

$product_vars =数组(数组(element_name‘=> 'band’、标题‘=> 'Band’、'options‘=> $bands、’占位符‘=>’$bands‘)、数组( 'element_name’=>‘颜色’、‘标题’=> 'Color‘、'options’=> $colors‘、’占位符‘=>’选择一个‘)、( 'element_name’=>‘色彩’、‘选项’=>$colors、‘占位符’=>‘选择一个’)。

然后,我们可以将以下内容用于表单:

代码语言:javascript
复制
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前端位于<form>标记之外,<form>标记不被设置为使用$_POST,尽管其他代码都是这样设置的,并且没有添加任何验证类型。我已经粘贴了我的全部代码,这是为我工作。

代码语言:javascript
复制
<?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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69610117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档