Registration code not working

Either I'm just being completely blind or my code is refusing to work.

Can't seem to get my registration form to work.
I know that all the names are correct as I've submitted an empty form and I'm getting all the error
messages I wrote back. e.g username is missing

I've checked that all the database values are correct and are going into the right table and yet I'm just getting back "query failed" so I know for a fact that something is wrong with one of the two sections where I've wrote "query failed" but I just can't see the problem...Anyway, here's my code:

reg.php
<form id="loginForm" name="loginForm" method="post" action="regcheck.php">
  <table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
    <tr>
      <th>First Name </th>
      <td><input name="FirstName" type="text" class="textfield" id="FirstName" /></td>
    </tr>
    <tr>
      <th>Last Name </th>
      <td><input name="Surname" type="text" class="textfield" id="Surname" /></td>
    </tr>
    <tr>
      <th width="124">Username</th>
      <td width="168"><input name="UserName" type="text" class="textfield" id="UserName" /></td>
    </tr>
    <tr>
      <th>Password</th>
      <td><input name="Password" type="password" class="textfield" id="Password" /></td>
    </tr>
    <tr>
      <th>Confirm Password </th>
      <td><input name="cpassword" type="password" class="textfield" id="cpassword" /></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input type="submit" class='button' name="Submit" value="Register" /></td>
    </tr>
  </table>
</form>
<?php
	if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
		echo '<ul class="err">';
		foreach($_SESSION['ERRMSG_ARR'] as $msg) {
			echo '<li>',$msg,'</li>'; 
		}
		echo '</ul>';
		unset($_SESSION['ERRMSG_ARR']);
	}
?>

Open in new window


and...

regcheck.php
<?php
	//Start session
	session_start();
	
	//Include database connection details
	require_once('config.php');
	
	//Array to store validation errors
	$errmsg_arr = array();
	
	//Validation error flag
	$errflag = false;
	
	//Connect to mysql server
	$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
	if(!$link) {
		die('Failed to connect to server: ' . mysql_error());
	}
	
	//Select database
	$db = mysql_select_db(DB_DATABASE);
	if(!$db) {
		die("Unable to select database");
	}
	
	//Function to sanitize values received from the form. Prevents SQL injection
	function clean($str) {
		$str = @trim($str);
		if(get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		return mysql_real_escape_string($str);
	}
	
	//Sanitize the POST values
	$FirstName = clean($_POST['FirstName']);
	$Surname = clean($_POST['Surname']);
	$UserName = clean($_POST['UserName']);
	$Password = clean($_POST['Password']);
	$cpassword = clean($_POST['cpassword']);
	
	//Input Validations
	if($FirstName == '') {
		$errmsg_arr[] = 'First name missing';
		$errflag = true;
	}
	if($Surname == '') {
		$errmsg_arr[] = 'Last name missing';
		$errflag = true;
	}
	if($UserName == '') {
		$errmsg_arr[] = 'Username missing';
		$errflag = true;
	}
	if($Password == '') {
		$errmsg_arr[] = 'Password missing';
		$errflag = true;
	}
	if($cpassword == '') {
		$errmsg_arr[] = 'Confirm password missing';
		$errflag = true;
	}
	if( strcmp($Password, $cpassword) != 0 ) {
		$errmsg_arr[] = 'Passwords do not match';
		$errflag = true;
	}
	
	//Check for duplicate UserName
	if($UserName != '') {
		$qry = "SELECT * FROM user WHERE UserName='$UserName'";
		$result = mysql_query($qry);
		if($result) {
			if(mysql_num_rows($result) > 0) {
				$errmsg_arr[] = 'Username already in use';
				$errflag = true;
			}
			@mysql_free_result($result);
		}
		else {
			die("Query failed");
		}
	}
	
	//If there are input validations, redirect back to the registration form
	if($errflag) {
		$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
		session_write_close();
		header("location: reg.php");
		exit();
	}

	//Create INSERT query
	$qry = "INSERT INTO user(FirstName, Surname, UserName, Password) VALUES('$FirstName','$Surname','$UserName','".md5($_POST['Password'])."')";
	$result = @mysql_query($qry);
	
	//Check whether the query was successful or not
	if($result) {
		header("location: register-success.php");
		exit();
	}else {
		die("Query failed");
	}
?>

Open in new window


If you can see the error, please do let me know as it's driving me mad.
As you can see, the  "Check for duplicate UserName" and "Create INSERT query" are the two
sections with "Query failed".

Thanks.
PSTCATAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Hugh McCurdyCommented:
Instead of this
<td><input name="FirstName" type="text" class="textfield" id="FirstName" /></td>
try
<td><input name="FirstName" type="text" class="textfield" name='FirstName' id="FirstName" /></td>
Hugh McCurdyCommented:
If that doesn't work, let's start debugging by adding a    var_dump ( $_POST );    in the vicinity of your calls to clean().

PSTCATAuthor Commented:
Nope. That gives a yellow highlight on the HTML and didn't change anything with the "Query Failed" error.

Thanks though.
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

PSTCATAuthor Commented:
The var_dump gives the following error...


array(6) { ["FirstName"]=> string(6) "tester" ["Surname"]=> string(4) "test" ["UserName"]=> string(6) "tester" ["Password"]=> string(7) "testing" ["cpassword"]=> string(7) "testing" ["Submit"]=> string(8) "Register" } Query failed
mankowitzCommented:
Also, see what mysql is telling you. Replace

die("Query failed");

Open in new window


with

die("Query failed with query $qry and error " . mysql_error() );

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
PSTCATAuthor Commented:
Ok it now works! Thanks so much.

I replaced that line and it told me there was a duplicate entry key
so I removed the user that  was in database (me) and now it works perfect.

Cheers!
Hugh McCurdyCommented:
It still may have helped.  Anyway, at this time, the $_POST variable is good.

In addition to mankowitz's suggestion, let's get more information.

Change

      //Create INSERT query
      $qry = "INSERT INTO user(FirstName, Surname, UserName, Password) VALUES('$FirstName','$Surname','$UserName','".md5($_POST['Password'])."')";
      $result = @mysql_query($qry);
to
      //Create INSERT query
      $qry = "INSERT INTO user(FirstName, Surname, UserName, Password) VALUES('$FirstName','$Surname','$UserName','".md5($_POST['Password'])."')";
        printf ( "qry = %s<br />\n", $qry );
      $result = @mysql_query($qry);

This will tell us what the query is trying to do.


Hugh McCurdyCommented:
I'm also suspicious about clean();

After the clean() section, print one of the variable.

printf  (  "FirstName = %s<br />\n", $FirstName );

Let's see if it matches the $_POST variable for 'FirstName'
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.