User registration code driving me nuts

My user rego code:

<?php
if (isset($_POST['register'])) {
	require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.php';
		$username = mysqli_real_escape_string($link, $_POST['username']);
		$email = mysqli_real_escape_string($link, $_POST['email']);
		$emailmatch = mysqli_real_escape_string($link, $_POST['emailmatch']);
		$password = mysqli_real_escape_string($link, $_POST['password']);
		$passwordmatch = mysqli_real_escape_string($link, $_POST['passwordmatch']);
			if (empty($username) || empty($email) || empty($emailmatch) || empty($password) || empty($passwordmatch)) { $errorempty = '1'; }
			else
				if (strlen($username) < 2 || strlen($username) > 25) { $errorusername = '1'; }
			else
				if (strlen($password) < 3 || strlen($password) > 55) { $errorpassword = '1'; }
			else
				if (strlen($email) < 3 || strlen($email) > 55) { $erroremail = '1'; }
			else
				if ($password != $passwordmatch) { $errorpasswordmatch = '1'; }
			else
				if ($email != $emailmatch) { $erroremailmatch = '1';}
			else
				if (!empty($username) && !empty($email) && !empty($emailmatch) && !empty($password) && !empty($passwordmatch)) {
				
							$checkuser = mysqli_query($link, "SELECT username FROM members WHERE username = '$username'");
								$result_user = mysqli_num_rows($checkuser);
									if ($result_user > 0) { $errorusernametaken = '1'; }
									
							$checkemail = mysqli_query($link, "SELECT email FROM members WHERE email = '$email'");
								$result_email = mysqli_num_rows($checkemail);
									if ($result_email > 0) { $erroremailtaken = '1'; }
									}
									
									else
									
									$mix = md5($password . 'salt');
									$sql = "INSERT INTO members SET username = '$regusername', email = '$regemail', password = '$mix'";
										if (!mysqli_query($link, $sql)) {
											$error = 'Error: ' . mysqli_error($link);
											include 'error.php';
											}
								else {include 'success.php'; exit(); }
}
?>

Everything works fine except one thing when the user actually succeeds in registering - the user actually gets put in the database if that is the case… but the password isn’t being put in:

'Notice: Undefined variable: mix in register.php on line 43'

I have finally got everything else working so that errors show up for the correct reason, and you can only register if the username and/or email isn’t taken etc.

I have been re-arranging and trying new things in this code all day long, and I’d love some help.

Feel free to tell me if my code sucks in general, I’m just learning. Sorry for the ugly formatting :stuck_out_tongue:

See how this goes for you

&lt;?php

function error($message, $use_file=false) {
    if (!$use_file) {
        die($message . '&lt;br /&gt;&lt;br /&gt;&lt;a href="javascript:history.go(-1)"&gt;Go back&lt;/a&gt;');
    } else {
        $error = $message;
        include 'error.php';
    }
}

if (isset($_POST['register'])) {
    require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.php';
    
    $regex = '/^[a-z0-9!#$%&\\'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\\'*+\\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+(?:[a-z]{2}|aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel)$/i';
    
    if ((!isset($_POST['username']) || !isset($_POST['email']) || !isset($_POST['emailmatch']) || !isset($_POST['password']) || !isset($_POST['passwordmatch'])) ||
        (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['emailmatch']) || empty($_POST['password']) || empty($_POST['passwordmatch']))) {
        error('One or more fields are invalid, please make sure all fields have a value!');
    }
    
    $username = mysqli_real_escape_string($link, $_POST['username']);
    $email = mysqli_real_escape_string($link, $_POST['email']);
    $emailmatch = mysqli_real_escape_string($link, $_POST['emailmatch']);
    $password = mysqli_real_escape_string($link, $_POST['password']);
    $passwordmatch = mysqli_real_escape_string($link, $_POST['passwordmatch']);
    
    if (strlen($username) &lt; 2 || strlen($username) &gt; 25) {
        error('The username you have entered is invalid, please make sure its 2 - 25 characters long!');
    } else if (strlen($password) &lt; 3 || strlen($password) &gt; 55) {
        error('The password you have entered is invalid, please make sure its 3 - 55 characters long!');
    } else if (!preg_match($regex, $email)) {
        error('The email address you entered is invalid!');
    } else if ($email != $emailmatch) {
        error('The confirmation email address you entered does NOT match the first email address!');
    } else if ($password != $passwordmatch) {
        error('The confirmation password you entered does NOT match the first password!');
    }

    $result = mysqli_query($link, "SELECT username FROM members WHERE username = '$username'");
    $user_numrows = mysqli_num_rows($result);
    mysqli_free_result($result);
    
    if ($user_numrows &gt; 0) {
        error('Sorry but the username you have chosen is already in use, please try another username!');
    }

    $result = mysqli_query($link, "SELECT email FROM members WHERE email = '$email'");
    $email_numrows = mysqli_num_rows($result);
    mysqli_free_result($result);
    
    if ($email_numrows &gt; 0) {
        error('Sorry but the email you have entered is already in use, please try another email address!');
    }
    
    if (!mysqli_query($link, "INSERT INTO members SET username = '$username', email = '$email', password = '" . md5($password . 'salt') . "'")) {
        $error = 'Error: ' . mysqli_error($link);
        error($error, true);
    } else {
        include 'success.php';
    }
}

?&gt;

Works great, thank you! :slight_smile:

Your welcome

Or not, and it’s a really weird problem.

the only lines giving me trouble are these:

$mix = md5($password . 'salt');
$sql = "INSERT INTO members SET username = '$username', email = '$email', password = '$mix'";
if (!mysqli_query($link, $sql)) {
$error = 'Error: ' . mysqli_error($link);
include 'error.php';
}

if I change $mix in the query to this, as suggested:

$sql = "INSERT INTO members SET username = '$username', email = '$email', password = '" . md5($password . 'salt') . "'";

it all works perfectly and I no longer get my original error. but in changing that, I obviously no longer need the first line ($mix =), so I remove it. but when I remove it, I now get THIS error when trying to register:

Notice: Undefined variable: sql in register.php on line 43

Warning: mysqli_query() [function.mysqli-query]: Empty query register.php on line 43

this just doesn’t make any sense to me at all.

ok let me start again, here is my ENTIRE register.php

<?php
session_start();
if (isset($_SESSION['username'])) {
	header('Location: /');
}
?>
<?php
if (isset($_POST['register'])) {
	require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.php';
	require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/func.php';
		$username = mysqli_real_escape_string($link, $_POST['username']);
		$email = mysqli_real_escape_string($link, $_POST['email']);
		$emailmatch = mysqli_real_escape_string($link, $_POST['emailmatch']);
		$password = mysqli_real_escape_string($link, $_POST['password']);
		$passwordmatch = mysqli_real_escape_string($link, $_POST['passwordmatch']);
			if (empty($username) || empty($email) || empty($emailmatch) || empty($password) || empty($passwordmatch)) { $errorempty = '1'; }
			else
				if (strlen($username) < 2 || strlen($username) > 25) { $errorusername = '1'; }
			else
				if (strlen($password) < 3 || strlen($password) > 55) { $errorpassword = '1'; }
			else
				if (strlen($email) < 3 || strlen($email) > 55) { $erroremail = '1'; }
			else
				if ($password != $passwordmatch) { $errorpasswordmatch = '1'; }
			else
				if ($email != $emailmatch) { $erroremailmatch = '1';}
			else
				if (!empty($username) && !empty($email) && !empty($emailmatch) && !empty($password) && !empty($passwordmatch)) {
				
							$checkuser = mysqli_query($link, "SELECT username FROM members WHERE username = '$username'");
								$result_user = mysqli_num_rows($checkuser);
									if ($result_user > 0) { $errorusernametaken = '1'; }
									
							$checkemail = mysqli_query($link, "SELECT email FROM members WHERE email = '$email'");
								$result_email = mysqli_num_rows($checkemail);
									if ($result_email > 0) { $erroremailtaken = '1'; }
									}
									
									else
									
					/* line 42 */				$sql = "INSERT INTO members SET username = '$regusername', email = '$regemail', password = '" . md5($password . 'salt') . "'";
										if (!mysqli_query($link, $sql)) {
											$error = 'Error: ' . mysqli_error($link);
											include 'error.php';
											}
								else {include 'success.php'; exit(); }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<title>website</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<link href="style1.css" rel="stylesheet" type="text/css"/>
</head>
	<body>
		<div id="wrapper">
		<div id="main">
		<div id="register">
			<form action="" method="post">
			<center>
			<?php if (isset($errorempty)) {
			echo 'Please fill out all required fields.' . '<br/>';
			}
			?>
			</center>
	Username:<input type="text" name="username"/><?php if (isset($errorusernametaken)) { echo 'Username is in use, please try again' . '<br/>'; } ?><?php if (isset($errorusername)) { echo 'Username must be between 3 and 25 characters.' . '<br/>'; } ?>
	Your Email:<input type="text" name="email"/><?php if (isset($erroremailtaken)) { echo 'Email is in use, please try again.' . '<br/>'; } ?><?php if (isset($erroremail)) { echo 'Email must be between 3 and 55 characters.' . '<br/>'; } ?>
	 Email again:<input type="text" name="emailmatch"/><?php if (isset($erroremailmatch)) { echo 'Emails do not match' . '<br/>'; } ?>
	Password:<input type="password" name="password"/><?php if (isset($errorpassword)) { echo 'Password must be between 3 and 55 characters' . '<br/>'; } ?>
	Password again:<input type="password" name="passwordmatch"/><?php if (isset($errorpasswordmatch)) { echo 'Passwords do not match.' . '<br/>'; } ?>
		<input type="submit" name="register" value="Go"/>
			</form>
		</div> <!-- end of register -->
		</div> <!-- end of main -->
			<?php include $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php'; ?>
		</div> <!-- end of wrapper -->
	</body>
</html>

So my form+code is all on one page, thus the reason I have created error variables and then checked to see which to display in the form instead of echo+exiting - it would just show a blank page with the error.

Now… this file works PERFECTLY, provided I have ANYTHING before line 42 as marked… (I could even just put $blah = $bleh;). That is what is driving me nuts.

As soon as I take away the random line I have before the INSERT, it says $SQL is an undefined variable. So for some reason that line is just not being read…?

There must be a reason why. Any ideas anyone? I want to fix what I have before I add yummy regex stuff etc… because what I have works, except for this one odd problem!

Oh and if anyone can tell me how to format my code with colors automatically(?) like sgtlegend did there, I would be grateful to be able to provide better pastes. heh

or not, all of a sudden it is just inserting into the database everytime, even if I input something that should cause an error.

I swear I didn’t even change anything. Restored the file from my ‘yay its working’ backup and same thing. Very confused right now. My head is about to explode, I guess I need to rework this entire thing. Really want to be able to do this in one file.

changed the bottom half of the code to this:

$checkuser = mysqli_query($link, "SELECT username FROM members WHERE username = '$username'");
$result_user = mysqli_num_rows($checkuser);
if ($result_user > 0) { $errorusernametaken = '1'; }
									
$checkemail = mysqli_query($link, "SELECT email FROM members WHERE email = '$email'");
$result_email = mysqli_num_rows($checkemail);
if ($result_email > 0) { $erroremailtaken = '1'; }
}
									
else
									
if (!isset($errorempty) && !isset($errorusername) && !isset($errorpassword) && !isset($erroremail) && !isset($errorpasswordmatch) && !isset($erroremailmatch) && !isset($errorusernametaken) && !isset($erroremailtaken)) {

$sql = "INSERT INTO members SET username = '$username', email = '$email', password = '" . md5($password . 'salt') . "'";
if (!mysqli_query($link, $sql)) {
$error = 'Error: ' . mysqli_error($link);
include 'error.php';
}
else { include 'success.php'; exit(); }
}

and now my errors are displaying correctly, and if there is any error it won’t insert the user. but now when there are no errors, the page just refreshes with no execution of the query.

I really hope someone smarter than me can tell me what I’m doing wrong lol.

I’m confused as i updated your code but you seem to have reverted back to your old code. Try the below as i updated it to set inline errors…

&lt;?php

if (isset($_POST['register'])) {
    require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.php';
    
    $errors = false;
    $regex = '/^[a-z0-9!#$%&\\'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\\'*+\\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+(?:[a-z]{2}|aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel)$/i';
    
    if ((!isset($_POST['username']) || !isset($_POST['email']) || !isset($_POST['emailmatch']) || !isset($_POST['password']) || !isset($_POST['passwordmatch'])) ||
        (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['emailmatch']) || empty($_POST['password']) || empty($_POST['passwordmatch']))) {
        $errors = true;
    }
    
    if (!$errors) {
        $username = mysqli_real_escape_string($link, $_POST['username']);
        $email = mysqli_real_escape_string($link, $_POST['email']);
        $emailmatch = mysqli_real_escape_string($link, $_POST['emailmatch']);
        $password = mysqli_real_escape_string($link, $_POST['password']);
        $passwordmatch = mysqli_real_escape_string($link, $_POST['passwordmatch']);
        
        if (strlen($username) &lt; 2 || strlen($username) &gt; 25) {
            $errors = true;
            $usernameError = 'The username you have entered is invalid, please make sure its 2 - 25 characters long!';
        } else if (strlen($password) &lt; 3 || strlen($password) &gt; 55) {
            $errors = true;
            $passwordError = 'The password you have entered is invalid, please make sure its 3 - 55 characters long!';
        } else if (!preg_match($regex, $email)) {
            $errors = true;
            $emailError = 'The email address you entered is invalid!';
        } else if ($email != $emailmatch) {
            $errors = true;
            $emailcError = 'The confirmation email address you entered does NOT match the first email address!';
        } else if ($password != $passwordmatch) {
            $errors = true;
            $passwordcError = 'The confirmation password you entered does NOT match the first password!';
        }
        
        if (!$errors) {
            $result = mysqli_query($link, "SELECT username FROM members WHERE username = '$username'");
            $user_numrows = mysqli_num_rows($result);
            mysqli_free_result($result);
            
            if ($user_numrows &gt; 0) {
                $usernameError = 'Sorry but the username you have chosen is already in use, please try another username!';
            }
            
            $result = mysqli_query($link, "SELECT email FROM members WHERE email = '$email'");
            $email_numrows = mysqli_num_rows($result);
            mysqli_free_result($result);
            
            if ($email_numrows &gt; 0) {
                $emailError = 'Sorry but the email you have entered is already in use, please try another email address!';
            }
            
            if (!mysqli_query($link, "INSERT INTO members SET username = '$username', email = '$email', password = '" . md5($password . 'salt') . "'")) {
                $error = 'Error: ' . mysqli_error($link);
                include 'error.php';
            } else {
                include 'success.php';
            }
            
            exit;
        }
    }
}

?&gt;
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt;
&lt;head&gt;
&lt;title&gt;website&lt;/title&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
&lt;link href="style1.css" rel="stylesheet" type="text/css" media="screen" /&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div id="wrapper"&gt;
    &lt;div id="main"&gt;
        &lt;div id="register"&gt;
            &lt;form action="&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;" method="post"&gt;
                &lt;?php
                if (isset($errors) && $errors) {
                    echo '&lt;font color="red" style="text-align: center;"&gt;One or more fields are invalid, please make sure all fields have a value!&lt;/font&gt;&lt;br /&gt;';
                }
                ?&gt;
                Username: &lt;input type="text" name="username" /&gt;
                &lt;?php echo isset($usernameError) ? '&lt;br /&gt;' . $usernameError : ''; ?&gt;&lt;br /&gt;
                Your Email: &lt;input type="text" name="email" /&gt;
                &lt;?php echo isset($emailError) ? '&lt;br /&gt;' . $emailError : ''; ?&gt;&lt;br /&gt;
                Email again: &lt;input type="text" name="emailmatch" /&gt;
                &lt;?php echo isset($emailcError) ? '&lt;br /&gt;' . $emailcError : ''; ?&gt;&lt;br /&gt;
                Password: &lt;input type="password" name="password" /&gt;
                &lt;?php echo isset($passwordError) ? '&lt;br /&gt;' . $passwordError  : ''; ?&gt;&lt;br /&gt;
                Password again: &lt;input type="password" name="passwordmatch" /&gt;
                &lt;?php echo isset($passwordcError) ? '&lt;br /&gt;' . $passwordcError  : ''; ?&gt;
                &lt;br /&gt;&lt;br /&gt;
                &lt;input type="submit" name="register" value="Go" /&gt;
            &lt;/form&gt;
        &lt;/div&gt; &lt;!-- end of register --&gt;
    &lt;/div&gt; &lt;!-- end of main --&gt;
    &lt;?php include $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php'; ?&gt;
&lt;/div&gt; &lt;!-- end of wrapper --&gt;

&lt;/body&gt;
&lt;/html&gt;

Thanks very much, it looks much nicer than my code (really curious as to mine doesn’t work… everything but inserting the user works really well!)

but it is doing the same thing mine used to do - inserting the user even if the username and/or email is already taken… :frowning:

the errors all work fine though (except username/email taken)

hmm

Woah I think I actually fixed mine, just took out the ‘else’ before my final query… seems to be working…!!!

now I can just implement your beautiful error handling, much prefer it over mine… thanks so much for all of your help!

(as soon as I post this it is going to stop working. :smiley: :D)