1

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"));
1
  • Expand on "breaks the page". Is there an error? What is it? Commented Aug 14, 2010 at 0:34

4 Answers 4

6

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());
Sign up to request clarification or add additional context in comments.

Comments

1

Should be:

mysql_query("INSERT INTO stats VALUES (".$userAgent.")");

3 Comments

This fixes the PHP error, but not the wrong SQL syntax and the SQL injection problem.
Downvoted due to sql injection. Sorry, but there's too much bad advice like this out there already.
So INSERT INTO stats VALUES (Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; de; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8) is a valid SQL statement?
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.