You would simply concatenate your query together using the data you receive from the form. Now you will definitely want to perform a LOT of validation, ensuring the operator is =, <, <=, >, or >=, and not an invalid value (even though it is a drop down; you need this!)
Same with the field names, you will want to compare the field name selected to ensure it is a valid field name (keep an array of field names or query SQL Server to get a list of column names to compare against).
Finally, sanitize your keyword by replacing a single quote with two single quotes, etc (I believe we talked about this before in a previous thread).
One other thing to consider is whether the user would want to perform an AND or OR condition between the 10 rows (or per row) in the query, so you may need to provide that option, or if it is always considered AND/OR, then you can forgo providing that option.
Your form can be setup a couple of different ways, I personally like to use an array approach.
HTML Code:
<form method="post" action="">
<select name="field_name[]">
<option value="">Select One</option>
<option value="contract_id">Contract ID</option>
...
</select>
<select name="operator[]">
<option value="">Select One</option>
<option value="<"><</option>
<option value="<="><=</option>
...
</select>
<input type="text" name="keyword[]" /><br />
<select name="field_name[]">
<option value="">Select One</option>
<option value="contract_id">Contract ID</option>
...
</select>
<select name="operator[]">
<option value="">Select One</option>
<option value="<"><</option>
<option value="<="><=</option>
...
</select>
<input type="text" name="keyword[]" /><br />
...
</form>
You can then loop through the fields in your code
PHP Code:
<?php
$queryIsValid = true;
$query = "SELECT * FROM table WHERE";
for ($i = 0; $i < sizeof($_POST['field_names']); $i++)
{
if (strlen(trim($_POST['field_names'][$i])) !== 0
&& strlen(trim($_POST['operator'][$i])) !== 0
&& strlen(trim($_POST['keyword'][$i])) !== 0
&& IsValidFieldName($_POST['field_names'][$i])
&& IsValidOperator($_POST['operator'][$i]))
{
$field_name = SanitizeFileName($_POST['field_names'][$i]);
$operator= SanitizeOperator($_POST['operator'][$i]);
$keyword= SanitizeKeyword($_POST['keyword'][$i]);
if ($i === 0)
{
$query .= " " . $field_name . " " . $operator . " '" . $keyword . "'";
}
else
{
$query .= " AND " . $field_name . " " . $operator . " '" . $keyword . "'";
}
}
else
{
$queryIsValid = false;
echo "required information missing or is invalid - query was not executed";
break;
}
}
if ($queryIsValid)
{
// execute query
}
?>
Bookmarks