tags:

views:

35

answers:

2

Working on my first PHP site (I'm mainly an ASP programmer), and I need to convert a querystring variable into a number I can then use to query a database. What's the best way to convert to a usable int (I tried intval() already but I keep getting 0 as a result) and also validate it (AKA no single quotes, blah blah) in PHP?

Thanks in advance!

A: 

You are probably trying to read input parameters for PHP script - I would recommend using

$_POST $_GET

arrays, as they hold all that info already parsed.

Tomasz Kowalczyk
I'm already using these, I just need to confirm that the input is a number before I add it to my SQL query.
MarathonStudios
+1  A: 

PHP allows for far more flexibility with types than ASP, and will convert between different types automatically.

The best way to ensure a number in your SQL is to use sprintf(), for example:

$sql = "SELECT name FROM users WHERE id = ".sprintf("%d", $_POST['userid']) ;

When inserting strings delivered by GET or POST into your SQL, you should use mysql_real_escape_string() (assuming your SQL is going to MySQL) to escape anything that needs escaping, so:

$sql = "SELECT id FROM users where name = ".sprintf("'%s'", mysql_real_escape_string($_GET['username'])) ;
Gus
What will sprintf() do if a string like "hello" is presented in the querystring instead of a number?
MarathonStudios
@MarathonStudios: `0`
Andrew Moore
Excellent, thanks!
MarathonStudios
If you're already using sprintf why not go all the way and do `$sql = sprintf("SELECT name FROM users WHERE id = %d", $_POST['userid']);`? Cleaner and no concatenation needed.
Andrew67