What I would like to achieve here is a user selects an operator, e.g. +, >, <, >= etc. and uses this in a Select statement in PHP.
MY HTML code:
<label for="grade">Grade: </label>
<select name="operator" id="operator">
<option value="">Select one</option>
<option value="<">Less than</option>
<optio开发者_开发技巧n value=">">More than</option>
<option value="=">Equals to</option>
</select>
<input type="text" name="grade" id="grade" size="2" maxlength="2">
</input>
My PHP code:
$operator = mysqli_real_escape_string($link, $_GET['operator']);
$grade = mysqli_real_escape_string($link, $_GET['grade']);
if ($grade != '') {
$where .= " AND grade . '$operator' . '$grade'";
}
What I would like to achieve is 'AND grade > 3'. '3' could be another number.
How could I change my codes to make PHP accepts it as a proper statement. Pardon my bad explanation here.
You shouldn't quote the operator:
$where .= " AND grade $operator '$grade'";
While you have escaped the grade, I would go further and check the operator is one of your expected operators, e.g.
if (($grade!='') && in_array($operator, array('>', '<', '=')))
{
....
}
i Think you should escape < > to html char codes.
You can set values to 1,2,3 and do:
$myarray = array( '<' , '>' , '=' );
the use
$myarray[$operator]
Wrong usage of escaping functions!
You know that operator could only be <
, >
, or =
and grade a number (without comma's or something).
This is a better validation:
$operator = isset($_GET['operator']) && is_string($_GET['operator']) && in_array($_GET['operator'], array('<', '>', '=')) ? $_GET['operator']: '';
$grade = isset($_GET['grade']) && is_string($_GET['grade']) && ctype_digit($_GET['grade']) ? $_GET['grade'] : '';
if($operator && $grade){
$where .= " AND grade $operator $grade";
}
It first checks if operator and grade exist in the $_GET array, then if it is a string (?operator[]= makes an array of it). Then it checks if operator is a valid operator (<, > or =) and grade is really a number.
I think the line for grade should be:
" AND grade $operator $grade "
精彩评论