簡體   English   中英

PHP 單頁表單處理

[英]PHP Single Page Form Processing

我是新來的,所以如果我誤解了如何在此處提交問題,請指出正確的方向。 另外,對不起,這太長了。

我正在處理一個 PHP 表單,該表單包含產品選擇的下拉列表以及客戶信息的字段。 我需要在單個頁面上處理它,而不是在單獨的頁面上處理它。 因此,在提交信息時,需要處理並顯示提交的信息並附上感謝信息。 此外,如果表格未完全填寫或需要填寫的方式,則應為不正確的字段顯示錯誤。 但是,用戶輸入的信息仍應保留。

我的工作和問題:我在下面分享了我的代碼(再次,抱歉,它應該全部在一頁上)。 我仍然遇到的問題是:

1.我收到警告錯誤,指出我有“未定義的數組鍵”。 我在提交表單之前和之后都得到了這個。 我已經在頂部定義了數組,所以我不確定為什么它們是未定義的。

2. T 恤下拉選項不保留任何選中的信息。 我已經嘗試在表單代碼本身和頂部為這些信息創建數組,但似乎無法堅持下去。 我還嘗試了另一種編碼選項,即回顯所選選項並將選擇放在 $_POST 或 $_GET 中。

3.如果我輸入了錯誤的電話號碼格式,我的錯誤捕獲將不起作用。 我最初收到錯誤消息,指出將其放入正確的格式,但如果我將信息放入正確的格式並提交,我仍然收到錯誤消息,並且電話號碼會重置為最初的狀態。 我知道它是從 $_GET 中提取的,但不知道為什么當它再次提交時它沒有更新 $_GET 以正確填充它。

4.最后,表單和正確提交后應填充的信息同時顯示在頁面上。 它應該是表格,直到正確填寫所有內容,然后是感謝消息,並在下面提交信息作為確認。 我已經嘗試將這些都用 if(empty....) 放入 PHP 中,如果按鈕沒有被按下,則回顯表單並檢查錯誤,如果它已被按下以檢查錯誤,如果沒有顯示感謝您提交信息。 但是,如果不正確,我無法使錯誤捕獲起作用,也無法獲取表單信息以保留在表單中。

也歡迎任何關於如何縮短我的代碼或格式的建議。 先感謝您!

<?php
    //variables
    $firstName= $lastName = $email = $phone = $address= $city = $state = $zip = "";
    $band = $bands = $color = $colors = $size = $sizes = $style = $styles = "";
    $error =  $message = "";
    $ec = 0;
    
    //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",);
    
    
    if(isset($_GET['firstName'])) $firstName = $_GET['firstName'];
    if(isset($_GET['lastName'])) $lastName = $_GET['lastName'];
    if(isset($_GET['email'])) $email = $_GET['email'];
    if(isset($_GET['phone'])) $phone = $_GET['phone'];
    if(isset($_GET['address'])) $address = $_GET['address'];
    if(isset($_GET['city'])) $city = $_GET['city'];
    if(isset($_GET['state'])) $state = $_GET['state'];
    if(isset($_GET['zip'])) $zip = $_GET['zip'];
    if(isset($_GET['colors'])) $zip = $_GET['colors'];
    if(isset($_GET['bands'])) $zip = $_GET['bands'];
    if(isset($_GET['sizes'])) $zip = $_GET['sizes'];
    if(isset($_GET['styles'])) $zip = $_GET['styles'];
?>


<!DOCTYPE html>
<html lang="en">
    <head>
        <title>T-Shirt Form</title>
        <link type="text/css" rel="stylesheet" href="css\style.css">
    </head>
    <body>          
        <!-- REMOVE WHEN READY TO DO CSS -->
        <style>
            p{padding:10px;margin:0px;}
            body{padding: 0px; margin: 20px;}
        </style>
        <!-- REMOVE WHEN READY TO DO CSS -->
        
                <h1>Order Form</h1><br>
        <form class = "form" action="" method="POST">
            <h4>T-Shirt Options</h4>
            
            <label>Band: </label>
                <select name="band" size="1">
                    <option selected = "selected">Choose One</option>
                    <?php
                        foreach($bands as $band)
                        {
                            echo "<option value = '.$band.'> $band </option>";
                        }
                    ?>
                </select>
    
            <label>Color: </label>
                <select name="color" size="1">
                    <option selected = "selected">Choose One</option>
                    <?php
                        foreach($colors as $color)
                        {
                            echo "<option value = '.$color.'> $color </option>";
                        }
                    ?>
                </select>
            
            <label>Size: </label>
                <select name="size" size="1">
                    <option selected = "selected">Choose One</option>
                    <?php
                        foreach($sizes as $size)
                        {
                            echo "<option value = '.$size.'> $size </option>";
                        }
                    ?>
                </select>
    
            <label>Style: </label>
                <select name="style" size="1">
                    <option selected = "selected">Choose One</option>
                    <?php
                        foreach($styles as $style)
                        {
                            echo "<option value = '.$style.'> $style </option>";
                        }
                    ?>
                </select>
            <br><br><br>
    
            <h3>Contact Information</h3>
            <label> First Name: <input type = "text" value="<?php echo $firstName;?>" id = "firstname" placeholder = "First Name" name ="firstName"></label>
            <label> Last Name: <input type = "text" value="<?php echo $lastName;?>" id = "lastname" placeholder = "Last Name" name = "lastName"></label>
            <label> Email: <input type = "text" value="<?php echo $email;?>" id = "email" placeholder = "Email Address" name = "email"></label>
            <label> Phone: <input type = "text" value="<?php echo $phone;?>" id = "phone" placeholder = "Phone Number" name = "phone"></label>
            <label> Address: <input type = "text" value="<?php echo $address;?>" id = "address" placeholder = "Address" name = "address"></label>
            <label> City: <input type = "text" value="<?php echo $city;?>" id = "city" placeholder = "City" name = "city"></label>
            <label> State: <input type = "text" value="<?php echo $state;?>" id = "state" placeholder = "State" name = "state"></label>
            <label> Zip Code: <input type = "text" value="<?php echo $zip;?>" id = "zip" placeholder = "Zip Code" name = "zip"></label>

            <input type = "reset" class="buttons">
            <input type="submit" name="submit-button" class="buttons">  
        </form>
        <br><br>
        
    <?php 
        $firstName = $_POST['firstName']; 
        $lastName = $_POST['lastName']; 
        $email_from = $_POST['email']; 
        $phone = $_POST['phone']; 
        $address = $_POST['address']; 
        $city = $_POST['city']; 
        $state = $_POST['state']; 
        $zip = $_POST['zip']; 
    
        //if there is an error reload with user information that was already filled out
        function died($error) 
        {
           if($error) header('location: ?error = '.$error.'&firstName='.$_POST['firstName'].'&lastName='.$_POST['lastName'].'&email='.$_POST['email'].'&phone='.$_POST['phone'].'&address='.$_POST['address'].'&city='.$_POST['city'].'&state='.$_POST['state'].'&zip='.$_POST['zip']);
        }
        
        //Check for errors or fields not filled out
        if(isset($_POST['submit-button'])) {
            if (empty($_POST['band']) && isset($_POST['band'])) 
            {
                $message .= '<li>Please select a band.</li>';
            }
            
            if (empty($_POST['color']) && isset($_POST['color'])) 
            {
                $message .= '<li>Please select a shirt color.</li>';
            }
            
            if (empty($_POST['size']) && isset($_POST['size'])) 
            {
                $message .= '<li>Please select a shirt size.</li>';
            }
            
            if (empty($_POST['style']) && isset($_POST['style'])) 
            {
                $message .= '<li>Please select a shirt style.</li>';
            }
            
            $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
           if(!preg_match($email_exp,$email_from)) 
           {
                $message .= '<li>Please enter a valid email address.</li>';
           }
         
            $string_exp = "/^[A-Za-z .'-]+$/";
            if(!preg_match($string_exp,$firstName)) 
            {
                $message .= '<li>Please enter a first name containing letters and spaces only.</li>';
            }
            
            $string_exp = "/^[A-Za-z .'-]+$/";
            if(!preg_match($string_exp,$lastName)) 
            {
                $message .= '<li>Please enter a last name containing letters and spaces only.</li>';
            }
          
           $num_exp = "/^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$/";
            if(!preg_match($num_exp,$phone)) 
            {
                $message .= '<li>Please enter a valid phone number in the following format (xxx)xxx-xxxx.</li>';
            }
            
            $num_exp = "/\d+ [0-9a-zA-Z ]+/";
            if(!preg_match($num_exp,$address)) 
            {
                $message .= '<li>Please enter an address.</li>';
            }
            
            $num_exp = "/^[A-Za-z .'-]+$/";
            if(!preg_match($num_exp,$city)) 
            {
                $message .= '<li>Please enter a city.</li>';
            }
            
            $num_exp = "/^[A-Za-z .'-]+$/";
            if(!preg_match($num_exp,$state)) 
            {
                $message .= '<li>Please enter a state.</li>';
            }
            
            $num_exp = "/^[0-9]*$/";
            if(!preg_match($num_exp,$zip))
            {
                $message .= '<li>Please enter a zip code containing 5 numbers.</li>';
            }
            if (strlen($zip) != 5)
            {
                $message .= '<li>Please enter a zip code containing 5 numbers.</li>';
            }
         
            if(strlen($message) > 0) 
            {
                died($message);
            }
        }
        
        //If there is an error, echo it here.
        if(isset($_GET['error_'])) $error = $_GET['error_'];
            echo "<br><br>";
            echo $error;
            echo $message;
    ?>
    
    <!---display processed information here--->
    <h3 class="subheaderone">Thank you for your order!</h3><br>
    <h3 class = "subheadertwo">Product:</h3>
    <div class = "output">
    
    <p><?php echo $_POST["$size"]." ".$_POST["$color"]." ".$_POST["$band"]." ".$_POST["$style"]; ?></p><br>
    
    <h3 class = "subheadertwo">Shipping & Contact Information:</h3>
    <p>Name: <?php echo $_POST["firstName"]." ".$_POST["lastName"]; ?></p>
    <p>Email: <?php echo $_POST["email"]; ?></p>
    <p>Phone Number: <?php echo $_POST["phone"]; ?></p>
    <p>Address: </p>
    <p><?php echo $_POST["address"]; ?></p>
    <p><?php echo $_POST["city"].", ".$_POST["state"]." ".$_POST["zip"]; ?></p><br>
    </div>
    <div class="another">
    <nav><a href="./products.php"> Submit Another Form</a></nav> 
    <div>
</body>
</html>

好的,這里有幾件事:

  • 您不需要頂部的變量分配。 這在 C 和其他語言中非常重要,但 PHP 不需要。

  • 你的if(isset($_GET['firstName'])) $firstName = $_GET['firstName']; 語句使用$_GET而您的<form>標簽使用$_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 = array( array( 'element_name' => 'band', 'title' => 'Band', 'options' => $bands, 'placeholder' => '選擇一個', ), array( 'element_name' => 'color', 'title' => 'Color', 'options' => $colors, 'placeholder' => '選擇一個', ), );

然后我們可以對表單使用以下內容:

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
}

希望這會有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM