Jump to content

mysql_real_escape_string


YMYL

Recommended Posts

Would you use it for an integer?

No. It is called mysql_real_escape_string() for a reason.

 

I checked and it returns an string, would that mess things up with a script?

$_GET/$_POST values are always string types. So,the input is already a string anyway.

 

PHP is a "loosely" typed language. That means it can (usually) convert variables to the proper types as needed. So you can do math operations on string variables if they contain numeric characters.

 

But, none of this means that you should not safeguard the user input from wreaking havoc on your queries. In this case you want the value to be an integer. So, use the functions within PHP to ensure it is an integer.

 

You can force the value to be an integer by using the intval() function or typecasting the value as in integer

$valueAsInt = intval($_GET['page']);
$typeCastAsInt = (int) $_GET['page'];

 

If the value cannot be converted to an integer value you will get 0. The other approach would be to validate that the value is a string that has the characters matching an integer value;

if(!ctype_digit())
{
   //Value is not a proper integer - do something
   // - provide error or force to default value, e.g. 1
}
else
{
   $page = $_GET['page'];
}

 

I would typically do this

//If post value is set, use intval of it, else default to 1
$page = (isset($_POST['page']) ? intval($_POST['page']) : 1;

//Assuming I know the max page number
//If page less than 1 or greater than max page default to 1
if($page<1 || $page > $maxPages)
{
   $page = 1;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.