How can I filter POST numeric values in php?
Question by user841823
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
<?php echo '<label for="Category">Category:</label>
<select name="category_id" size="1" ><br />';
$sql = "SELECT id, name FROM category ORDER BY name";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
echo "<option value="".$row['name']."$".$row['id']."">".$row['name']."</option>n ";
}
echo '</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.
$option = explode("$", $_POST['category_id']);
enter code here
Answer by Phil
Are you just trying to retrieve the category name and ID from the posted, $
delimited category_id
field?
If so, then this should do it
$option = explode("$", $_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 like
if (!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.
Answer by Starx
Not sure, If i got you correctly. If you are trying to receive the name and id of the product from the same select box, using your technique
echo "<option value="".$row['name']."$".$row['id']."">".$row['name']."</option>n ";
Change this line to this. Just replace $
with “_” for simplicty
echo "<option value="".$row['name']."_".$row['id']."">".$row['name']."</option>n ";
Then while processing it
$category_id = $_POST['category_id'];
$carr = explode("_",$category_id);
$category = $carr[0];
$id = $carr[1];
//now verify them
if((int)$id>0) { //id is valid number
// and so on