开发者

Handling errors on php contact form

The 开发者_如何学Pythonbelow code is working great for handling errors for text fields in my contact form, but how do I get this same method to work for dropdown select option boxes and textareas?

<input type="text" name="name" value="<?php if($errors){echo $name;} ?>" id="name" size="30" />

For example:

<textarea name="message" value="<?php if($errors){echo $message;} ?>" id="message" rows="10" cols="40"></textarea>

does not work.


In the case of a textarea, you have to put the default value within the tag itself. For example:

<textarea name="message" id="message" rows="10" cols="40"><?php if($errors){echo $message;} ?></textarea>


This is how you should do the INPUT: it's like you have it, but you really should escape the user-provided content with htmlentities (or htmlspecialchars, etc.) in case they had quotes, brackets, etc. in the text that would be interpreted as HTML characters by the browser. That's just good practice.

<input type="text" name="name" id="name" size="30"
  value="<?php if ($errors) { echo $name; } ?>" />

This is how you should do the TEXTAREA: put the content between the textarea open/close tags. And make sure to escape it properly too.

<textarea name="message" id="message" rows="10" cols="40"
  ><?php if ($errors) { echo htmlentities($message); } ?></textarea>

This is how you might handle the SELECT tag. I've spaced out the code for readability so you can understand what's going on. Basically you just have to output selected="selected" in the OPTION element you want to be selected.

<select>
  <option value = "val1" 
    <?php if ($error && ($selval=="val1")) { echo 'selected="selected"'; } ?>
  >
    Option Label 1
  </option>
  <option value = "val2" 
    <?php if ($error && ($selval=="val2")) { echo 'selected="selected"'; } ?>
  >
    Option Label 2
  </option>
  ... (additional <option> tags here) ...
</select>


for the text area:

textarea name="message" id="message" rows="10" cols="40"><?php if($errors){echo $message;} ?></textarea>

For the dropdown, you'll need to do something like this:

<select>
  <option value = "1" <? echo ($errror && $myposted_val == "1") ? "selected = \"selected\"" : ""; ?></option>
</select>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜