0

Im trying to insert data into a table in MySQL. I found/modified some code from w3Schools and still couldn't get it working. Heres what I have so far:

<?php
$rusername=$_POST['username']; 
$rname=$_POST['name'];
$remail=$_POST['emailadr'];
$rpassword=$_POST['pass'];
$rconfirmpassword=$_POST['cpass'];

if ($rpassword==$rconfirmpassword) {

    $con = mysql_connect("host","user","password");
    if (!$con)
     {
         die('Could not connect: ' . mysql_error());
     }
        mysql_select_db("mydbname ", $con);
    }

    mysql_query("INSERT INTO members (id, username, password)
    VALUES ('4', $rusername, $rpassword)");


?>

Did I mistype something? To my understanding "members" is the name of the table. If anyone knows whats wrong I appreciate the help.

Thanks

4
  • Why are you adding 4 as id? Just put id as auto-incrementing and you won't have to deal with it anymore. Also, id should be an integer, so no need of using quotes there Commented May 22, 2010 at 0:04
  • 2
    This is a SQL injection vulnerability. Please use parameterized queries (see PHP docs for PDO: php.net/pdo), or at the very least escape input with a function like mysql_real_escape_string. Commented May 22, 2010 at 0:12
  • I just put 4 in to test it. Now it generates a random number. And yes, I have heard of SQL injection and I do use mysql_real_escape_string for the login. I haven't added it to the create account yet though. Commented May 22, 2010 at 0:24
  • this reminds me of: xkcd.com/327 Commented May 22, 2010 at 0:35

2 Answers 2

4

The query resulted from your code is:

INSERT INTO members (id, username, password) VALUES ('4', rusername, rpassword)

Note that in SQL string must be surrounded by '.

So update your code to this:

mysql_query("INSERT INTO members (id, username, password)
             VALUES ('4', '$rusername', '$rpassword')");
Sign up to request clarification or add additional context in comments.

Comments

0

And your database name?

mysql_select_db("mydbname ", $con);

Even though it's called mydbname there's a weird space char in there..

You can also do

mysql_query("use mydbname", $con);

EDIT

Try to include the database connection flag in the query, and also replace '4' (that as nico said if it's an autoincrement key [id], it must be an integer, without quotes) by null:

mysql_query("INSERT INTO members VALUES
            (null, '$rusername', '$rpassword');", $con);

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.