Reputation: 3170
I'm trying to add some simple user data into a database via a webpage written in PHP, but the following code (more specifically, line three) breaks the page. Am I using the wrong MySQL function? I'm pretty sure my query is formatted correctly.
mysql_query("CREATE TABLE stats ( userAgent CHAR(20) )");
$userAgent = $_SERVER["HTTP_USER_AGENT"];
mysql_query("INSERT INTO stats VALUES ("$userAgent"));
Upvotes: 1
Views: 1074
Reputation: 11628
The PHP error can be fixed like this (note the dot, it's used to "glue" the strings together):
mysql_query("INSERT INTO stats VALUES (".$userAgent.")");
Also, you should do some SQL Injection protection, the user-agent string is user-defined (there are tools to modify it), so it needs to be sanitized. Further, the user-agent is a string so you need to put it in between single quotes.
mysql_query("INSERT INTO stats VALUES ('" . mysql_real_escape_string($userAgent) . "')");
Another important thing would be error handling - echoing the error description is necessary to find bugs in your SQL syntax.
mysql_query("INSERT INTO stats VALUES ('" . mysql_real_escape_string($userAgent) . "')")
or die("MySQL Error: " . mysql_error());
Upvotes: 6
Reputation: 98559
Eton B. has the right answer, but please note that the code you've written will leave you at the mercy of little Bobby Tables.
DON'T DO THIS
Upvotes: 1
Reputation: 29508
Are you escaping your $userAgent
variable?
Data must be "cleaned" before going anywhere near your database.
<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());
// Clean
$userAgent = mysql_real_escape_string($_SERVER["HTTP_USER_AGENT"]);
// Query
mysql_query("INSERT INTO stats VALUES ($userAgent)");
?>
Upvotes: 0
Reputation: 6291
Should be:
mysql_query("INSERT INTO stats VALUES (".$userAgent.")");
Upvotes: 1