IS multiplies by 1 safe way to clear numerical values ​​from SQL injections?

I am wondering if I have a value that I know should be numeric, multiplies it by 1 safe method to clear it?

function x($p1){ $p1*=1; sql="select * from t where id ={$p1}"; //run query.. } 

Although my example uses an ID, this is used for many types of numeric values ​​that I have in my application (there may be money, maybe pai, etc.).

+4
source share
6 answers

I do not understand why this will not happen. But what is wrong with using prepared statements? This will always be safer than using PHP variables directly in SQL statements.

+2
source

You can use is_numeric ()

+2
source

I am sure that there is a more "suitable" way, but for the scope of your question, I would say yes. If some string is passed, PHP will interpret it as zero when performing a mathematical operation.

0
source

You can also use is_int ()

0
source

While this will work, intval seems to be the best solution. http://php.net/manual/en/function.intval.php . Your intention is likely to be more apparent to someone else reading your code.

If you want to check if a value is numeric before converting it to int, use is_numeric ( http://php.net/manual/en/function.is-numeric.php ). It will check strings that are numeric as well as integers. For example, if a number was returned from an input text form via AJAX, it could be a string. In this case, is_int will return false, but is_numeric will return true.

EDIT

Now that I know that you are using DECIMAL for the MySQL column type, you can do something like this:

 function getItem($pValue) { if (!is_numeric($pValue)) { return false; } $Query = sprintf ( 'SELECT * FROM %s WHERE %s = %.2f', 'TableName', 'Price', $pValue ); // Do something with $Query } 
0
source

It works most of the time, since it will pass strings integer or double, but you have to be careful. It will work correctly for scalar values. However, if you do this:

 x(new stdClass); 

You will receive E_NOTICE . This is not so bad, is it? It:

 x(array()); 

And you get the types E_ERROR , Unsupported operands, and the script ends.

You might think that this is not so bad, but a fatal error at the wrong time can leave your system in an unstable state, for example, losing link integrity or leaving an incomplete sequence of requests.

Only you know if a case like the one above can happen. But if this data comes from the user in any way, I would go with Murphy's law on this matter and not trust him.

0
source

Source: https://habr.com/ru/post/1380916/


All Articles