AAA
AAA

Reputation: 3168

How do i add mysql_real_escape_string(): to this?

Here's the code:

  //check if the starting row variable was passed in the URL or not
  if (!isset($_GET['pg']) or !is_numeric($_GET['pg'])) {
 //we give the value of the starting row to 0 because nothing was found in URL
  $startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)mysql_real_escape_string($_GET['pg']);
}

Whenever I try to add mysql_real_escape_string(); to the $_GET['pg') in the !isset, the code doesn't execute and i get no error message.

Upvotes: 0

Views: 350

Answers (3)

hakre
hakre

Reputation: 197624

You want to have an integer value that is 0 or greater; that is 0 if the input is invalid:

$startrow = max(0, isset($_GET['pg']) ? $_GET['pg'] : 0);

The mysql_real_escape_string() is not needed for integer values. Depending on your coding style, this is possible in PHP as well:

$startrow = max(0, @$_GET['pg']);

If you're using PHP 5.4 it performs even quite well.

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270609

Don't cast the pg value to an int. Instead, verify that it contains an integer value, or don't execute the query. If you didn't plan on executing a query (which we can't see), then mysql_real_escape_string() is entirely the wrong tool since it needs a connection.

The appropriate thing to do is validate that the contents of $_GET['pg'] is an integer, not to escape it.

Since is_numeric() will return TRUE for non-integer real numbers, I tend to use ctype_digit() to validate positive integers. If you need the possibility of negative integers as well, you can use ctype_digit(abs($_GET['pg']))

if (!isset($_GET['pg']) or !ctype_digit($_GET['pg'])) {
   // it wasn't an integer
   // initialize to your default value
}
else {
  // $_GET['pg'] *has to be a valid int* or we wouldn't have entered the else block
  // no need to escape or further process it - it's safe to use
}

Upvotes: 2

Okizb
Okizb

Reputation: 99

mysql_real_escape_string requires a connection to database (second parameter), if it is not provided, last opened connection will be used - see:

http://php.net/manual/en/function.mysql-real-escape-string.php

might it be that at this point of your code no connection to the database was created? in that case you should see a warning (check if your php configuration allows displaing warnings)

Upvotes: 0

Related Questions