views:

46

answers:

3

I have a simple feedback form PHP script that I would like to enhance by adding the $_SERVER[HTTP_USER_AGENT] data to the row in the database that I'm saving.

I keep getting parse errors when I try a simple insert, passing '$_SERVER[HTTP_USER_AGENT]' as a typical string. Should I bundle it in some way, so that the characters used in that Server variable are not triggering such errors?

(The INSERT query runs fine without that field, btw.)

Thanks.

+1  A: 

My bet is that there is a ' in the user agent strings that are causing the parser error.

The User-Agent string returned to PHP is under control of the local browser, which means that you need to treat it no differently from regular user input. A malicious user or a user who has been infected by a virus/trojan/worm could change the user agent string to cause an SQL injection attack. At the very least, you need to escape it (with mysql_real_escape_string() for example. My bet is that once you do this, your parser errors should also go away. Better yet, try to move to using prepared statements if your system allows this.

Andrew
Thanks for explaining the solution and its reasoning.
Yaaqov
+1  A: 

Does

mysql_query("
INSERT INTO
    db_table
VALUES (
    ...
    '" . mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']) . "'
    ...
)");

not work? Can you show us your whole query? What are the exact error-messages?

faileN
Do you always write your whole code in a form of single operator?
Col. Shrapnel
What do you mean by "single operator"? If you mean that, I don't specify the fields and only use the `VALUES`-Operator: the answer is "no"
faileN
A: 

Without an actual error massage it's hard to say what particular problem you encounter with.
But to solve all possible issues,

  • First of all, you must read an official manual page to make yourself understand PHP strings syntax: http://php.net/types.string

  • Then, you have to understand Mysql proper syntax. I've explained it already here

  • Finally, you have to put everything together

like this:

$agent = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);
$sql   = "INSERT INTO `table` set useragent = '$agent'";
$res   = mysql_query($sql) or trigger_error(mysql_query.$sql);

Running your queries this way you'll never have any problem. Or comprehensive error message at least.

Col. Shrapnel