如何验证PHP表单中的数组?

问题描述:

I'm fairly new to php and was wondering how do I validate the array for the states and where do I place the php code at? I already did the address part but I'm stuck at the states part.

Here is the validation code.

if (isset($_POST['contact_info_submitted'])) { // Handle the form.

    $address = mysqli_real_escape_string(htmlentities($_POST['address']));

}

Here is the form code.

<li><label for="address-1">Address 1: </label><input type="text" name="address-1" id="address-1" size="25" class="input-size" value="<?php if (isset($_POST['address'])) echo $_POST['address']; ?>" /></li>

<li><label for="state-province">State/Province: </label>
<?php
echo '<select name="state-province" id="state-province">' . "
";
    foreach($state_options as $option) {
        if ($option == $state) {
            echo '<option value="' . $option . '" selected="selected">' . $option . '</option>' . "
";
            } else {
              echo '<option value="'. $option . '">' . $option . '</option>'."
";
            }
        }
            echo '</select>';

?>
</li>
<li><input type="submit" name="submit" value="Save Changes" class="save-button" />
    <input type="hidden" name="contact_info_submitted" value="true" />

我对php很新,我想知道如何验证数组的状态以及我在哪里放置 php代码在? 我已经完成了地址部分,但是我被困在状态部分。 p>

这是验证码。 p>

  if(isset)  ($ _POST ['contact_info_submitted'])){//处理表单。
 
 $ address = mysqli_real_escape_string(htmlentities($ _ POST ['address'])); 
 
} 
  code>  
 
 

这是表单代码。 p>

 &lt; li&gt;&lt; label for =“address-1”&gt;地址1:&lt;  ; / label&gt;&lt; input type =“text”name =“address-1”id =“address-1”size =“25”class =“input-size”value =“&lt;?php if(isset($)  _POST ['address']))echo $ _POST ['address'];?&gt;“  /&gt;&lt; / li&gt; 
 
&lt; li&gt;&lt; label for =“state-province”&gt;州/省:&lt; / label&gt; 
&lt;?php 
echo'&lt; select name =“ 州 - 省“id =”州 - 省“&gt;”  。  “
”; 
 foreach($ state_options as $ option){
 if($ option == $ state){
 echo'&lt; option value =“'。$ option。'”selected =“selected”  &GT;”  。  $选项。  '&LT; /选项&GT;'  。  “
”; 
}其他{
 echo'&lt; option value =“'。$ option。'”&gt;'  。  $选项。  '&lt; / option&gt;'。“
”; 
} 
} 
 
回音'&lt; / select&gt;'; 
 
?&gt; 
&lt; / li&gt; 
&lt; li&gt;&lt;  input type =“submit”name =“submit”value =“Save Changes”class =“save-button”/&gt; 
&lt; input type =“hidden”name =“contact_info_submitted”value =“true”/&gt;  
  code>  pre> 
  div>

If you're wondering how to check if someone submitted a valid value for state just check to see if there value they posted is in your array of states. If it's not there it's not valid:

if (!in_array($_POST['state-province'], $state_options)) {
    // not valid
}

If you're just trying to store in the a database like the other form values it's no different then any text field:

if (isset($_POST['contact_info_submitted'])) { // Handle the form.
    $state= mysqli_real_escape_string($_POST['state-province']);
}