Thursday, 16 October 2014

PHP: How can I filter POST numeric values in php?

Numeric values..
$price = $_POST['price'];
 $zipcode = $_POST['zipcode'];


How can I filter two fields passing through a single select tag field called category_id that uses the explode() to recieve the values from this category_id field.

Form 
<label for="Category">Category:</label> 
<select name="category_id" size="1" >
<?php
 $sql = "SELECT id, name FROM category ORDER BY name"; 
 $rs = mysql_query($sql);
 while($row = mysql_fetch_array($rs)) {
 echo "<option value=\"".$row['name']."quot;.$row['id']."\">".$row['name']."</option>\n "; 
}
?>
</select>
The way I receive the category_id field with explode but don't know how to filter it since it is a numeric and data field at the same time.




Answer1:


Are you just trying to retrieve the category name and ID from the posted, $ delimited category_idfield?

If so, then this should do it$option = explode("quot;, $_POST['category_id']); $name = $option[0]; $id = $option[1];


I would be more inclined to just set the ID in the <option> value attribute and fetch the name from the database or a pre-fetched associative array.
Update

If you're wanting to validate that field, you could try something likeif (!preg_match('/^[a-zA-Z0-9]+\$\d+$/', $_POST['category_id'])) { // not valid }


I wouldn't attempt to filter out invalid characters on that field. Validation and error conditions are more concise.

0 comments:

Post a Comment