views:

33

answers:

4

Hi guys,

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>
                    <option 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.

A: 

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]
killer_PL
Thanks killer. I will go with another solution.
dave
+2  A: 

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('>', '<', '=')))
{
    ....
}
Paul Dixon
Thanks Paul for a simple and succinct answer.
dave
dave
ah yes, I left that as, erm, an exercise for the reader ;)
Paul Dixon
+1  A: 

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.

Lekensteyn
Thanks Lek. I will go with another solution.
dave
+1  A: 

I think the line for grade should be:

" AND grade $operator $grade "

spbfox
thanks spbfox. I would go with Paul's solution here.
dave
Understandable. I would do the same.
spbfox