开发者

Where should I do mysql_real_escape_string?

I have a quick question about mysql_real_escape_string. Where should I use it?

I have a *.php file with form that is redirecting it to itself, but that file is using another file that has class in it with function Add(params);

So should I escape strings when they are submitted?

$catName = mysql_real_escape_string($_POST['edtCatAddName']);

Or should I escape strings in my class?

$catName = mysql_real_escape_string($catName);

Or perhaps both these situations are 开发者_JAVA技巧wrong and I need to do something else? I've tried to escape just my query like this

$query = mysql_real_escape_string("INSERT INTO cat (catName, catDescr, catImg, catSubLevel, catSubID) VALUES ('$catName', '$catDescr', '$catImgURL', $catSubLevel, $catSubID)");

But it's not too good because this way my query won't go since catName and some other variables are string type and I need to add ' before and after them and these chars are escaped.

Any advice? I'm very new to this...

So if I use PDO then all I have to do is

$STH = $DBH->prepare("my raw, not escaped query");  
$STH->execute(); 

and I can feel secure?


nowhere, you should use PDO prepared statements instead to protect you against SQL-injections.


When to use mysql_real_escape_string()

Actually mysql_real_escape_string() is used while sanitize a input from a user. So you should (at least) use it everywhere a user can input anything that goes into a query. It is also very suggested to use Prepared Statements.

What Prepared Statements are

Basically they are sql queries that are very safe. Let's make an example.

SELECT UserName FROM user WHERE UserUID = X

Is a simple query. Let's say that the X is a variable that come from a $_GET input. Some users could add to X everything. Even a 1; and then start a new query. This technique is called SQL Injection.

Now with mysql_real_escape_string() you solve part of this problem, and it's quite safe. But Prepared statements tell the server that

SELECT UserName FROM user WHERE UserUID =

Is something like a static part, and then that X is a variable. In this way the server is kinda prepared to execute such a query, and nothing else, considering any input in X like an input. In this way you have not to worry about user inputs at all.


you can do:

$catName = mysql_real_escape_string($_POST['catName']);

or use mysql_real_escape_string() directly in your query.

For values which are expected to be a number (integer, float) - you can either use intval($var) for integers or floatval($var) for floats.

BUT:
never use mysql_real_escape_string() for the entire query - that's simply wrong ;-)

EDIT:
I forgot to mention: the best is to use PDO(PHP Data Objects) -> http://de.php.net/PDO


Don't. Use parameters in queries using mysqli or PDO.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜