Chris
Chris

Reputation: 193

Is this the correct way to insert data into database with PHP?

I'm trying to insert user input into a database with the following code.

mysql_query("INSERT INTO 'users' ('Email', 'Username', 'Password') VALUES ($email, $username, $password)");

There are no errors, but the database never seems to get the code inserted. Am I doing something wrong?

Here is my entire code, HTML and all

<?php

    DEFINE ('SERVER', 'localhost');
    DEFINE ('PASSWORD', '');
    DEFINE ('USER', 'root');

    $email = $_POST['email'];
    $username = $_POST['username'];
    $password = SHA1($_POST['pass']);

    if(isset('submitted')
    {

    if($email && $username && $password)
    {
        $to = '[email protected]'
        $subject = 'subject'
        $body = 'there was an error connecting to the db, please check it.'
        $dbconnect = @mysql_connect(SERVER, USER, PASSWORD) or die("NO WORK!");
        $query = "USE practice" 
        mysql_query($query);

        mysql_query("INSERT INTO users (Email, Username, Password)
             VALUES ('$email', '$username', '$password')") or die(mysql_erorr());
    }
    }

?>
<html>

<form action = "" method = "post">
<label>Email Address</label>
<input type="text" name="email" /> <br />
<label>Desired Username</label>
<input type="text" name="username" /> <br />
<label>Password</label>
<input type="password" name="pass" /> <br />
<input type="submit" value="Register"  />
<input type="hidden" name="submitted" value=1 />
</form>

</html>

Upvotes: 1

Views: 702

Answers (3)

Tomas
Tomas

Reputation: 59525

Probably you should also enclose the values in apostrophes, and probably also you shall not use apostrophes for table and field names, but rather backticks ` or nothing in your case!

mysql_query("INSERT INTO users (Email, Username, Password)
             VALUES ('$email', '$username', '$password')")

But also be sure to properly escape the values of these variables! Not only because of SQL injection but mostly just to assure the proper SQL syntax. Imagine user with the name O'Brian - he would have resulted in SQL error.

Upvotes: 2

Chris Cates
Chris Cates

Reputation: 121

Also when declaring namespaces in the mySQL database. You should put backticks ` like this. So

   mysql_query("INSERT INTO users (`Email`, `Username`, `Password`)
         VALUES ('$email', '$username', '$password')") or die(mysql_erorr());

Otherwise, your code looks solid.

Upvotes: 0

AjayR
AjayR

Reputation: 4179

You may be getting some errors but not displaying probably due to following line the spell error with mysql_error as mysql_erorr

   mysql_query("INSERT INTO users (Email, Username, Password)
             VALUES ('$email', '$username', '$password')") or die(mysql_erorr());

Just try to fix that and see if you get some database errors so that it will be easy to trace out and fix it.

Upvotes: 0

Related Questions