views:

187

answers:

7

im having some problem with this code:

if (count($_POST)) {

$username = mysql_real_escape_string($_POST['username']);
$passwd = mysql_real_escape_string($_POST['passwd']);

mysql_query("INSERT INTO users (username, password)
             VALUES ($username, $passwd)");

}

<form method="post">

<p><input type="text" name="username" /></p>
<p><input type="password" name="passwd" /></p>

<p><input type="submit" value="Register me!" /></p>

</form>

i am connected to db
the users column ID is auto_increment

I get this when adding or die mysql_error in sql statement: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' )' at line 2

+14  A: 

You're missing quotes around the inserted values:

mysql_query("INSERT INTO users (username, password)
             VALUES ('$username', '$passwd')");
cletus
Isn't this a recipe for SQL injection?
Lasse V. Karlsen
The OP has mysql_real_escape_string() in his code already.
cletus
+2  A: 

surround both with single quotes

mysql_query("INSERT INTO users (username, password)
         VALUES ('$username', '$passwd')");
Dinah
+1  A: 

what is the type of fields username and password ? strings ? wrap with "

Haim Evgi
+2  A: 

The error message tells you you have a syntax error in your SQL in line 2. So something about the code

VALUES ($username, $passwd)

is wrong. Specifically you need quote characters around the parameters:

VALUES ('$username', '$passwd')
Mark Pim
+2  A: 

Try putting ' marks around the variables in the insert:

mysql_query("INSERT INTO users (username, password)
             VALUES ('$username', '$passwd')");
Paul
A: 

Others gave you the right answer.

Maybe here, you can add another variable so you can see the problem next time. And, next time, don't forget to test your query in a frontend for MySQL (MySQL Query Browser, PHPMyAdmin or so...)

$sql = "INSERT INTO users (username, password)
             VALUES ($username, $passwd)";

if(mysql_query($sql) === false)
{
    echo 'Error with my query : '.$sql;
    echo mysql_error();
}
mere-teresa
+1  A: 

A safer way to do this would be to use a prepared statement. Something like this:

$statement = $db_connection->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$statement->bind_param("s", $username);
$statement->bind_param("s", $passwd);
$statement->execute();

I used the following web page to get this snipped: http://www.petefreitag.com/item/356.cfm and it has more information about using the bind_param method. (This example is also for php5). The concept of using prepared statements is not limited to php and is widely used in many languages for both performance and security optimizations.

Mike Farmer