How to sanitise and store a decimal in sql databse

Viewed 63

I am new to sql and php but I am trying to figure out how I can safely store a decimal value that I take from an HTML form, sanitise it in php and then send it to an sql database. Currently, I am casting the HTML value to a float and using FILTER_SANITIZE_NUMBER_FLOAT for my sanitizing. The sql data value type is decimal(10,5). But when I store -2.5 into the database it comes out as -25.00000000. I know most of my code is right because when I take other values from the same form, sanitise them and then enter them into the databse it works fine.

    $Goal_howmch = (float) filter_input(INPUT_POST, 'How_much', FILTER_SANITIZE_NUMBER_FLOAT);
    
    <label for="How much"><b>How much: </b></label>
                    <select name="How_much" id="How much" default="0" required>
                        <option value=-10>-10%</option>
                        <option value=-7.5>-7.5%</option>
                        <option value=-5>-5%</option>
                        <option value=-2.5>-2.5%</option>
                        <option value=0 selected>0%</option>
                        <option value=2.5>2.5%</option>
                        <option value=5>5%</option>
                    </select>

1 Answers

Although it's specifically mentioned in the above documentation, because many seem to find this unintuitive it's worth pointing out that FILTER_SANITIZE_NUMBER_FLOAT will remove the decimal character unless you specify FILTER_FLAG_ALLOW_FRACTION:

<?php
$number_string = '12.34';

echo filter_var( $number_string, FILTER_SANITIZE_NUMBER_FLOAT ); // 1234

echo filter_var( $number_string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ); // 12.34
?>

Source: https://www.php.net/manual/en/filter.filters.sanitize.php#125563

Related