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@example.com'
$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>
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!
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.