开发者

Convert querystring to int in PHP

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() 开发者_Go百科already but I keep getting 0 as a result) and also validate it (AKA no single quotes, blah blah) in PHP?


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'])) ;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜