Jorm
Jorm

Reputation:

INSERT INTO wont work!

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

Upvotes: 0

Views: 6373

Answers (7)

Mike Farmer
Mike Farmer

Reputation: 2992

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.

Upvotes: 1

mere-teresa
mere-teresa

Reputation: 434

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();
}

Upvotes: 1

Paul
Paul

Reputation: 9561

Try putting ' marks around the variables in the insert:

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

Upvotes: 2

Mark Pim
Mark Pim

Reputation: 10082

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')

Upvotes: 2

Haim Evgi
Haim Evgi

Reputation: 125614

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

Upvotes: 1

Dinah
Dinah

Reputation: 54077

surround both with single quotes

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

Upvotes: 2

cletus
cletus

Reputation: 625377

You're missing quotes around the inserted values:

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

Upvotes: 14

Related Questions