Sheikh Emad Uddin Sheikh Emad Uddin - 1 year ago 35
SQL Question

Canit insert into my MYSQL table

I am trying to make a registration form in which I have connected to the database and it can also check whether the username is unique or not but unfortunately, I can't insert the new data in my table.
I would really appreciate if anyone could help me with this.

error_reporting(E_ALL ^ E_DEPRECATED);
include '';
if(isset($_POST['submit'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['password2']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);

//md5 password
$password_hash = md5($password);

//check to see if the fields are empty
if(empty($username) || empty($password)|| empty($firstname)|| empty($lastname)) {
echo "Not all fields filled!<br /><br />";

//check if password is equal

if($password != $password2) {
echo "Your Passwords Do Not Match.<br />";
} else {
$query = "SELECT `username` From `users` WHERE username='$username'";
$result = mysql_query($query);

if(mysql_num_rows($result) ==1) {
echo "Sorry, that user has already exists.";
} else {
$query1= mysql_query("INSERT INTO `users` ('',username,password,firstname,lastname) VALUES ('','$username', '$password_hash', '$firstname', '$lastname'");
if($result1 = mysql_query($query1)) {
echo "Registered Successfully";
} else {
echo "Sorry, You could not Register";

<form action="" method="POST">
Username:<br />
<input type="text" name="username" /><br /><br />

Password:<br />
<input type="password" name="password" /><br /><br />

Confirm Password:<br />
<input type="password" name="password2" /><br /><br />

First Name:<br />
<input type="text" name="firstname" /><br /><br />

Last Name:<br />
<input type="text" name="lastname" /><br /><br />

<input type="submit" value="Register" name="submit" />

Answer Source

Your INSERT statement is missing a closing parenthesis.

$query1= mysql_query("INSERT INTO ... '$lastname'");

$query1= mysql_query("INSERT INTO ... '$lastname')");

By the way, I find it easier when doing a single-row INSERT to use an alternative syntax, so the column names and the value are matched up:

$query1= mysql_query("INSERT INTO `users` SET

That's easier to make sure you have the columns matched up to the right variables. Also there's no closing parenthesis to worry about.

See for details on this syntax.

You should also abandon the deprecated mysql extension, and use PDO instead. Read this nice tutorial:

And Jay Blanchard is correct that your code is insecure. Security, like correctness, is not an add-on feature. You mention you are a beginner, but you should not start developing bad habits. Read