Jump to content

[SOLVED] Does this data need to be made safe for a database


keeps21

Recommended Posts

I have the following code which takes the ID from the URL and runs a query to select names froma a database with that ID.

 

<?php
// example url = http://localhost/index.php?id=1

if (isset($_GET['id']) && is_numeric($_GET['id'])) { // id is set and is a number
$id = $_GET_id; // Should I bother doing $id = mysql_real_escape_string($_GET_id); 

$query = "SELECT name FROM database WHERE id={$id}";
$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {
	echo $row['name'].'<br />';
}
}
?>

 

What I need to know is that is there any point in running mysql_real_escape_string on the ID before using it in the database in this case as if ID is not a number the query won't be run anyway?

 

 

I have the following code which takes the ID from the URL and runs a query to select names froma a database with that ID.

 

<?php
// example url = http://localhost/index.php?id=1

if (isset($_GET['id']) && is_numeric($_GET['id'])) { // id is set and is a number
$id = $_GET_id; // Should I bother doing $id = mysql_real_escape_string($_GET_id); 

$query = "SELECT name FROM database WHERE id={$id}";
$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {
	echo $row['name'].'<br />';
}
}
?>

 

What I need to know is that is there any point in running mysql_real_escape_string on the ID before using it in the database in this case as if ID is not a number the query won't be run anyway?

 

 

 

I think it would be good practice to do it, but that's just me. NEVER TRUST user input.

 

Just because it's not a form, it's still user input from a conceptual sense.....

 

I would like to hear other point of views on this...

 

This is wrong:

$id = $_GET_id;

 

should be

$id = $_GET['id'];

 

Using is_numeric is good enough, although I would additionally cast the value to (int)

 

Oops just typed it out to post on here, hadn't tested it, yeah I was thinking about casting to (int), or could I use is_int instead of is_numeric?

Values in $_GET are strings by default, so for index.php?ID=1

is_int($_GET['ID']); //FALSE
is_int((int)$_GET['ID']); //TRUE

 

Hey, so doing this:

 

is_int((int)$_GET['ID']); //TRUE

 

Basically sets the value of $_GET['ID'] to an integer right?

 

Could I also do this?

 

$string = '1';

 

$number = (int) $string;

 

 

 

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.