Sheikh Emad Uddin Sheikh Emad Uddin - 4 months ago 11
PHP Question

Cant insert in 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.

<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include 'connect.inc.php';
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 />";
exit();
}

//check if password is equal

if($password != $password2) {
echo "Your Passwords Do Not Match.<br />";
exit();
} 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.";
exit();
} 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" />
</form>

Answer

You want to probably insert the user id in the database.Define it as Autoincrement e remove the blank data from the query below:

Before:

$query1= mysql_query("INSERT INTO `users` ('',username,password,firstname,lastname) VALUES ('','$username',     '$password_hash', '$firstname', '$lastname'");

After:

$query1= mysql_query("INSERT INTO `users` (username,password,firstname,lastname) VALUES ('$username',     '$password_hash', '$firstname', '$lastname')") or die(mysql_error());

And you need also to replace the line with the code if($result1 = mysql_query($query1)) { by if($result1) {