开发者

Inserting Data into MySQL Table via PHP

I'm trying to add some simple user data into a database via a webpage written in PHP开发者_Python百科, 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());


Should be:

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)");
?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜