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"));
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());
应该:
mysql_query("INSERT INTO stats VALUES (".$userAgent.")");
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
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)");
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.