开发者

Seeking assistance with Escaping Data for MySQL queries

Please don't send me a link to php.net referencing mysql_real_escape_string as the only response. I have read through the page and while I understand the general concepts, I am having some trouble based on how my INSERT statement is currently built.

Today, I am using the following:

$sql = "INSERT INTO tablename VALUES ('', 
                                      '$_SESSION['Member1FirstName'], 
                                      '$_SESSION['Member1LastName'], 
      开发者_如何学C                                '$_SESSION['Member1ID'], 
                                      '$_SESSION['Member2FirstName'], 
                                      '$_SESSION['Member2LastName'], 
                                      '$_SESSION['Member2ID'] ....)

and the list goes on for 20+ members with some other values entered. It seems most people in the examples already have all their data stored in an array.

On my site, I accept form inputs, action="" is set to self, php validation takes place and if validation passes, data is stored into SESSION variables on page 2 then redirected to the next page in the process (page 3) (approximately 8-10 pages in the whole process).


You seem to already know that you should be using mysql_real_escape_string but I guess you don't know how to use. You need to apply it for each user supplied string you insert into your SQL. The following example should clarify this:

$sql = "INSERT INTO tablename VALUES ('', '" .
    mysql_real_escape_string($_SESSION['Member1FirstName']) . "', '" .
    mysql_real_escape_string($_SESSION['Member1LastName']) . "', '" .
    etc..

Or alternatively look into prepared statements and bind parameters for an easier (and faster) solution.


1) you're missing your closing single-quote and vars aren't replaced inside of single quotes.

2) mysql_real_escape_string is the answer, but try it with sprintf:

$sql = sprintf("INSERT INTO tablename VALUES ('', '%s', '%s', '%d' )",
               mysql_real_escape_string( $_SESSION['Member1FirstName']),
               mysql_real_escape_string( $_SESSION['Member1LastName']),
               $_SESSION['Member1ID']); // %d forced it as a digit

http://us2.php.net/manual/en/function.sprintf.php


Why can't you use mysql_real_escape_string?

You can also use a regexp to only allow certain characters that would be expected in a name

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜