2011-04-17 195 views
0

我是新來的編碼和PHP的世界。選擇了一些基礎知識之後,我把一個表格放在一起。我確信有很多有效的方法來編寫一個頁面,但是看到我已經把我所學到的東西放到了一起,在用戶發佈頁面之後,我有困難的選擇多選下拉列表,例如請記住用戶選擇的內容。這是我的整個代碼。PHP下拉多選擇

<?php 
//Process form variables 

//Validate if the form has been submitted 
if(isset($_POST['submit'])) { 

    //Validate if the form elements were completed 
    $fname = isset($_POST['fname']) ? $_POST['fname'] : ''; 
    $lname = isset($_POST['lname']) ? $_POST['lname'] : ''; 
    $email = isset($_POST['email']) ? $_POST['email'] : ''; 
    $gender = isset($_POST['gender']) ? $_POST['gender'] : ''; 
    $updates = isset($_POST['updates']) ? $_POST['updates'] : ''; 
    $media = isset($_POST['media']) ? $_POST['media'] : ''; 
    $comments = isset($_POST['comments']) ? $_POST['comments'] : ''; 

    //Place error messages in an array 
    $errormsg = array(); 

    if(empty($fname)) { 
      $errormsg[0] = 'Please specify your first name. It\'s blank.'; 
     } 

    if(empty($lname)) { 
      $errormsg[1] = 'Please specify your last name. It\'s blank.'; 
     } 

    if(empty($email)) { 
      $errormsg[2] = 'Please provide an email address. It\'s blank.'; 
    } 

    if(empty($gender)) { 
     $errormsg[3] = 'Please select a gender. It\'s blank.'; 
    } 

    if(empty($updates)) { 
     $errormsg[4] = 'Please select how we can contact you. It\'s blank.'; 
    } 

    if(empty($media)) { 
     $errormsg[5] = 'Please select where you heard about us. It\'s blank.'; 
    } 

    if(empty($comments)) { 
     $errormsg[6] = 'Please tell us what you think of us. It\'s blank.'; 
    } 

    //Return list of error messages 
    foreach($errormsg as $errormsg) { 
     echo $errormsg . '<br />'; 
    } 

    //Debug 
    print_r($_POST['media']); 
} 

?> 
<html> 
    <head> 
     <title>Sample Registration Form</title> 
    </head> 

    <body> 
     <h2>Sample Registration Form</h2> 

      <form name="registration" method="post" action="registration.php"> 
       <div> 
        First Name: <br /> 
        <input type="text" name="fname" value="<?php if(!empty($_POST['fname'])) { echo $fname; } ?>"> 
       </div> 

       <div> 
        Last Name: <br /> 
        <input type="text" name="lname" value="<?php if(!empty($_POST['lname'])) { echo $lname ; } ?>"> 
       </div> 

       <div> 
        Email Address: <br /> 
        <input type="text" name="email" value="<?php if(!empty($_POST['email'])) { echo $email; } ?>"> 
       </div> 

       <div> 
        Gender: <br /> 
        <?php 
        //Generate gender array 
        $gender = array('male', 'female'); 
        $countgender = count($gender); 

        for($start=0;$start < $countgender;$start=$start+1) { 

         $status = ''; 

         if(isset($_POST['submit'])) { 
          if($_POST['gender'][0] == $gender[$start]) { 
           $status = 'checked'; 
           // echo $gender[$start]; 
          } 
         } 

         $genderform = '<input type="radio" name="gender[]" value="'. $gender[$start] . '" '. $status. '>' . $gender[$start]; 
         echo $genderform; 

        }      

         // foreach($gender as $gender) { 

          // $status = ''; 

          // if(isset($_POST['submit'])) { 

           // if($_POST['gender'][0] == $gender) { 
            // $status = 'checked'; 
           // } 
          // } 

          // $genderform = '<input type="radio" name="gender[]" value="' .$gender . '" ' . $status .'>'. $gender . ''; 
          // echo $genderform; 
         // } 
        ?> 
       </div> 

       <div> 
        Would you like to receive updates from us? <br /> 
        <?php 
        $updates = array(0 => 'newsletter', 1 => 'email', 2 => 'sms'); 

        foreach($updates as $updatekeys => $updatevalues) { 

         $status = ''; 

         if(!empty($_POST['updates'][$updatevalues]) == $updatevalues) { 
          $status = 'checked'; 
          // echo $_POST['updates'][$updatevalues]; 

         } 

         echo '<input type="checkbox" name="updates[' . $updatevalues . ']" value="'. $updatevalues. '" '. $status . '>'.$updatevalues; 
        } 

        ?> 
       </div> 

       <div> 
        How did you hear about us? <br /> 

        <select name="media[]" multiple> 
        <?php 

         $media = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure'); 

         foreach($media as $mediakey => $mediavalue) { 

          $mediaform = '<option value="'. $mediavalue . '">'.$mediavalue.'</option>'; 
          echo $mediaform; 

         } 
        ?> 
        </select> 
       </div> 

       <div> 
        Tell us what you think: <br /> 
        <textarea name="comments" cols="50" rows="10"><?php if(!empty($_POST['comments'])) { echo $comments; } ?></textarea> 
       </div> 

       <div> 
        <input type="submit" name="submit" value="submit"> 
       </div> 
      </form> 
    </body> 
</html> 

編輯

,大家好,我已經更新了我的代碼,以反映下面的一些建議。讓我知道如果頁面更好編碼。我沒有包含像$ start ++這樣的建議,只是因爲我試圖理解它的含義。我喜歡儘可能縮短編碼,但看到我只是在學習,最好能夠打好基礎。

<?php 
//Initialize session 
session_start(); 

//Generate session id 
echo session_id() . '<br />'; 

//Process form variables 

//Validate if the form has been submitted 
if(isset($_POST['submit'])) { 

    //Validate if the form elements were completed 
    $fname = isset($_POST['fname']) ? $_POST['fname'] : ''; 
    $lname = isset($_POST['lname']) ? $_POST['lname'] : ''; 
    $email = isset($_POST['email']) ? $_POST['email'] : ''; 
    $gender = isset($_POST['gender']) ? $_POST['gender'] : ''; 
    $updates = isset($_POST['updates']) ? $_POST['updates'] : ''; 
    $media = isset($_POST['media']) ? $_POST['media'] : ''; 
    $comments = isset($_POST['comments']) ? $_POST['comments'] : ''; 

    //Place error messages in an array 
    $errormsg = array(); 

    if(empty($fname)) { 
      $errormsg[0] = 'Please specify your first name. It\'s blank.'; 
     } 

    if(empty($lname)) { 
      $errormsg[1] = 'Please specify your last name. It\'s blank.'; 
     } 

    if(empty($email)) { 
      $errormsg[2] = 'Please provide an email address. It\'s blank.'; 
    } 

    if(empty($gender)) { 
     $errormsg[3] = 'Please select a gender. It\'s blank.'; 
    } 

    if(empty($updates)) { 
     $errormsg[4] = 'Please select how we can contact you. It\'s blank.'; 
    } 

    if(empty($media)) { 
     $errormsg[5] = 'Please select where you heard about us. It\'s blank.'; 
    } 

    if(empty($comments)) { 
     $errormsg[6] = 'Please tell us what you think of us. It\'s blank.'; 
    } 

    //Return list of error messages 
    foreach($errormsg as $errormsg) { 
     echo $errormsg . '<br />'; 
    } 

    //Debug 
    // print_r($_POST['media']); 
} 

?> 
<html> 
    <head> 
     <title>Sample Registration Form</title> 
    </head> 

    <body> 
     <h2>Sample Registration Form</h2> 

      <form name="registration" method="post" action="registration.php"> 
       <div> 
        First Name: <br /> 
        <input type="text" name="fname" value="<?php if(!empty($_POST['fname'])) { echo $fname; } ?>"> 
       </div> 

       <div> 
        Last Name: <br /> 
        <input type="text" name="lname" value="<?php if(!empty($_POST['lname'])) { echo $lname ; } ?>"> 
       </div> 

       <div> 
        Email Address: <br /> 
        <input type="text" name="email" value="<?php if(!empty($_POST['email'])) { echo $email; } ?>"> 
       </div> 

       <div> 
        Gender: <br /> 
        <?php 
        //Generate gender array 
        $gender = array('male', 'female'); 
        $countgender = count($gender); 

        for($start=0;$start < $countgender;$start=$start+1) { 

         $status = ''; 

         if(isset($_POST['submit']) && !empty($_POST['gender'])) { 
          $status = in_array($gender[$start], $_POST['gender']) ? 'checked' : ''; 
         } 

         $genderform = '<input type="radio" name="gender[]" value="'. $gender[$start] . '" '. $status. '>' . $gender[$start]; 
         echo $genderform; 

        }      

        ?> 
       </div> 

       <div> 
        Would you like to receive updates from us? <br /> 
        <?php 
        $updates = array(0 => 'newsletter', 1 => 'email', 2 => 'sms'); 

        foreach($updates as $updatekeys => $updatevalues) { 

         $status = ''; 

         if(isset($_POST['submit']) && !empty($_POST['updates'])) { 
          $status = in_array($updatevalues, $_POST['updates']) ? 'checked' : ''; 
         } 

         // if(!empty($_POST['updates'][$updatevalues]) == $updatevalues) { 
          // $status = 'checked'; 
          // echo $_POST['updates'][$updatevalues]; 

         // } 

         echo '<input type="checkbox" name="updates[' . $updatevalues . ']" value="'. $updatevalues. '" '. $status . '>'.$updatevalues; 
        } 

        ?> 
       </div> 

       <div> 
        How did you hear about us? <br /> 

        <select name="media[]" multiple> 
        <?php 

         $media = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure'); 

         foreach($media as $mediakey => $mediavalue) { 

          $status = in_array($mediavalue,$_POST['media'])? 'selected' : ''; 

          $mediaform = '<option value="'. $mediavalue . '" '. $status .'>'.$mediavalue.'</option>'; 
          echo $mediaform; 

         } 
        ?> 
        </select> 
       </div> 

       <div> 
        Tell us what you think: <br /> 
        <textarea name="comments" cols="50" rows="10"><?php if(!empty($_POST['comments'])) { echo $comments; } ?></textarea> 
       </div> 

       <div> 
        <input type="submit" name="submit" value="submit"> 
       </div> 
      </form> 
    </body> 
</html> 
+0

和有什麼問題 – 2011-04-17 02:01:26

+0

當我提交表單時,多下拉/列表框不保留其值。我曾嘗試過,而且做循環無濟於事。 – PeanutsMonkey 2011-04-17 02:02:44

+0

你需要在選中的選項中回顯selected =「selected」,然後在post數組中返回 – 2011-04-17 02:04:36

回答

2

可以使用in_array功能檢查是否選擇$媒體的數組中的當前$ mediavalue - 但你需要與媒體來源陣列選擇另一名稱,因爲它會用用戶選擇覆蓋$ media變量。例如:

$mediaTypes = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure'); 
foreach($mediaTypes as $mediakey => $mediavalue) { 
    $mediaform = '<option value="'. $mediavalue . '" ' 
    . (in_array($mediavalue, $media) ? 'selected' : '') . '>' . $mediavalue.'</option>'; 
    echo $mediaform; 
} 

有幾個建議稍做修改代碼,以及:

  1. 你不需要在陣列中使用的數字 - 它複製的默認行爲,所以$ mediaTypes =陣列(0 =>'internet',1 =>'小冊子',2 =>'brochure');可以是$ mediaTypes =數組('internet','小冊子','小冊子');
  2. 未設置性別時,$ _POST ['gender']會導致通知「未定義索引:性別」。
  3. $ start = $ start + 1可以壓縮到$ start ++;
  4. 最好是重複使用的,而不是訪問$ _POST與用戶輸入的變量直接
+0

謝謝AlexAtNet。 @magma幫助了更容易遵循的代碼,正如前面提到的,我不知道in_array做什麼,何時使用它等等。您介意對代碼進行詳細說明嗎? 這是@岩漿的示例 '的foreach($媒體如$ mediakey => $ mediavalue){ $選擇= in_array($ mediavalue,$ _ POST [ '媒體']) 「選擇」: 「」;? $ mediaform =''。$ mediavalue。''; echo $ mediaform; }' – PeanutsMonkey 2011-04-17 02:58:25

+0

是的,我知道我得到的錯誤未定義索引。我打算在解決記住用戶爲列表框選擇的內容的問題後進行糾正。感謝您的建議。 任何你推薦重用變量的理由嗎? – PeanutsMonkey 2011-04-17 03:00:32

+0

@PananutsMonkey:AlexAtNet的代碼是相同的,他也提供了重要的建議。 「in_array」檢查給定值是否包含在現有數組中。在我們的例子中,如果是這樣,我們將'selected'關鍵字添加到html標記中,以便在呈現時保持選中狀態。 – magma 2011-04-17 03:02:57

1

試試這個:

foreach($media as $mediakey => $mediavalue) { 

    $selected=in_array($mediavalue,$_POST['media'])?"selected":""; 

    $mediaform = '<option '.$selected.' value="'. $mediavalue . '">'.$mediavalue.'</option>'; 

    echo $mediaform; 

} 
+0

非常感謝,但我不知道什麼in_array特別是在你的例子中的代碼構造,如$ mediavalue,$ _ POST ['media']。 $ status = in_array($ mediavalue,$ _ POST ['media'])? 'selected':''; 你介意闡述嗎? – PeanutsMonkey 2011-04-17 02:55:55

0

基於下拉的形式輸出,設置一個$ _SESSION [「變量」]的像做:

if (isset($_SESSION['variable'])) { 
// if exists 
} 
else { 
// if doesn't exist 
} 

你甚至可以包含其他基於不同參數的elseif語句。然後使用else作爲錯誤句柄。