Ive been given this code that registers users, ive got all the other parts working great with the login side but this is causing me problems. I dabble but not fluent in php.

This page is my register.php page. What i need is a register page that has the form on and when its filled out the "reg success" "reg failed" "username already taken" messages appear on the same page

Thanks in advance

<?php
session_start(); 
include("database.php");
include("login.php");

/**
 * Returns true if the username has been taken
 * by another user, false otherwise.
 */
function usernameTaken($username){
   global $conn;
   if(!get_magic_quotes_gpc()){
      $username = addslashes($username);
   }
   $q = "select username from customer where username = '$username'";
   $result = mysql_query($q,$conn);
   return (mysql_numrows($result) > 0);
}

/**
 * Inserts the given (username, password) pair
 * into the database. Returns true on success,
 * false otherwise.
 */
function addNewUser($username, $password){
   global $conn;
   $q = "INSERT INTO customer (Firstname, Surname, Company, Email, Type, Tel, Mob, username, password) VALUES ('$_POST[first]', '$_POST[surn]', '$_POST[comp]', '$_POST[email]', '$_POST[type]', '$_POST[tel]', '$_POST[mob]', '$username', '$password')";
   return mysql_query($q,$conn);
}

/**
 * Displays the appropriate message to the user
 * after the registration attempt. It displays a 
 * success or failure status depending on a
 * session variable set during registration.
 */
function displayStatus(){
   $uname = $_SESSION['reguname'];
   if($_SESSION['regresult']){
	   
?>

<h1>Registered!</h1>
<p>Thank you <b><?php echo $uname; ?></b>, your information has been added to the database, you may now <a href="index.php" title="Login">log in</a>.</p>

<?php
   }
   else{
?>

<h1>Registration Failed</h1>
<p>We're sorry, but an error has occurred and your registration for the username <b><?php echo $uname; ?></b>, could not be completed.<br>
Please try again at a later time.</p>

<?php
   }
   unset($_SESSION['reguname']);
   unset($_SESSION['registered']);
   unset($_SESSION['regresult']);
}

if(isset($_SESSION['registered'])){
/**
 * This is the page that will be displayed after the
 * registration has been attempted.
 */
?>
<html>
<title>Registration Page</title>
<body>

<?php displayStatus(); ?>

</body>
</html>

<?php
   return;
}

/**
 * Determines whether or not to show to sign-up form
 * based on whether the form has been submitted, if it
 * has, check the database for consistency and create
 * the new account.
 */
if(isset($_POST['subjoin'])){
   /* Make sure all fields were entered */
   if(!$_POST['user'] || !$_POST['pass']){
      die('You didn\'t fill in a required field.');
   }

   /* Spruce up username, check length */
   $_POST['user'] = trim($_POST['user']);
   if(strlen($_POST['user']) > 30){
      die("Sorry, the username is longer than 30 characters, please shorten it.");
   }

   /* Check if username is already in use */
   if(usernameTaken($_POST['user'])){
      $use = $_POST['user'];
      die("Sorry, the username: <strong>$use</strong> is already taken, please pick another one.");
   }

   /* Add the new account to the database */
   $md5pass = md5($_POST['pass']);
   $_SESSION['reguname'] = $_POST['user'];
   $_SESSION['regresult'] = addNewUser($_POST['user'], $md5pass);
   $_SESSION['registered'] = true;
   echo "<meta http-equiv=\"Refresh\" content=\"0;url=$HTTP_SERVER_VARS[PHP_SELF]\">";
   return;
}
else{
/**
 * This is the page with the sign-up form, the names
 * of the input fields are important and should not
 * be changed.
 */
?>
<html>
<title>Registration Page</title>
<body>
<h1>Register</h1>
<form action="<?php echo $HTTP_SERVER_VARS['PHP_SELF']; ?>" method="post">
<table align="left" border="0" cellspacing="0" cellpadding="3">
<tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr>
<tr><td>Password:</td><td><input type="password" name="pass" maxlength="30"></td></tr>
<tr><td colspan="2" align="right"><input type="submit" name="subjoin" value="Join!"></td></tr>
</table>
</form>
</body>
</html>

<?php
}
?>

Dani AI

Generated

A concise, safer pattern is to process the POST on the same file, set a single status/message variable, and render that message above the form. That keeps the form and any feedback on one page (no meta-refresh redirects or extra session flags). Use prepared statements (PDO or mysqli), password_hash for passwords, server-side validation, and htmlspecialchars() when outputting user data. This both fixes the immediate UX request and removes several security/compatibility problems present in older examples.

A minimal pattern (replace DSN/credentials and expand validation as needed):

<?php
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $user = trim($_POST['user'] ?? '');
  $pass = $_POST['pass'] ?? '';

  if ($user === '' || $pass === '') {
    $message = 'Required fields missing.';
  } else {
    $pdo = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'dbuser', 'dbpass', [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);

    $stmt = $pdo->prepare('SELECT id FROM users WHERE username = ?');
    $stmt->execute([$user]);

    if ($stmt->fetch()) {
      $message = 'Username already taken.';
    } else {
      $hash = password_hash($pass, PASSWORD_DEFAULT);
      $stmt = $pdo->prepare('INSERT INTO users (username,password,email) VALUES (?,?,?)');
      $stmt->execute([$user, $hash, $_POST['email'] ?? null]);
      $message = 'Registration successful — please log in.';
    }
  }
}
?>
<!-- echo htmlspecialchars($message) above the form -->

Troubleshooting and hardening notes:

  • Add a UNIQUE index on username and handle duplicate-key errors (prevents race conditions).
  • Never use plain MD5 for passwords; use password_hash/password_verify.
  • Use server-side validation (length, allowed chars, valid email) and client-side for convenience only.
  • When showing the username back in a message, escape it with htmlspecialchars.
  • ’s idea to check existence first is valid as a concept, but it should be implemented with prepared statements and a unique DB constraint for robustness.
  • Prefer PDO or mysqli over deprecated mysql_* functions so the code stays maintainable and secure.

This approach keeps messages on the same page, removes insecure practices, and makes the flow easier to maintain.

ok. see this code

if($username)
{

$select=mysql_query("select * from registration where username='$username'");
$count=mysql_num_rows($select);

if($count>0)
{
echo "username already exists";
}
else
{
//write insert query
}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.