I'm trying to execute a query using PHP and mongodb using inputs from a form.
<form method="post" action="search.php">
<tr><td>Firm</td><td><input type="text" name="firm" /></td></tr>
<tr><td>City</td><td><input type="text" name="city" /></td></tr>
<tr><td>State</td><td><input type="text" name="state" /></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Search" /></td></tr>
</form>
If all of the form fields are filled, I can do this easily (on the search.php page)
extract($_POST);
$query = array("firm" => $firm, "city" => $city, "state" => $state);
$fields = array("firm");
$cur = $collection->find($query,$fields);
But what if one or more of the fields is empty? Is there an easy way to construct the query such that only non-empty fields are included?
Thanks,
mcdermott
What about:
$query = array();
foreach ($_POST as $key => $value)
{
if (isValid($value))
{
$query[$key] = $value;
}
}
This way you just have to make sure that the form field names are the same as the field names of your data source. Of course you can do the validation before you loop over the already validated array.