Forum Moderators: coopster

Message Too Old, No Replies

Trouble creating a registration form for my website. New to Php.

         

matthayzon89

3:13 am on Sep 21, 2011 (gmt 0)

10+ Year Member



Hello,
I am new to php and I am creating a website for practice.

I am trying to create a user login system and i ran into a problem, I basically created a registration page for my practice website and I would like to make sure all the usernames that are registered on my website are unique.

I am using strcmp after the user click 'submit' and php script runs (comparing all the usernames in the sql database to that of a new user). If it returns zero then someone else already selected that user name and the user needs to select a new one.

So, im making my php script redirect to the registration form and I would like for it to have all most all the information the user typed in 'saved' so the user can select a new username and does not have to retype all the other information in.

My main problem is redirecting to the registration form and having the information that the user previously typed in 'saved' in the occurrence of selecting a username that is taken.

Any suggestions or advice on whats the best way to achieve this?


Thanks in advance.
-Matt

penders

7:27 am on Sep 21, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



If your form processing script is a different script to the one that displays your form and you are redirecting back to your form, then I think you will need to temporarily store your form data in a session (eg. $_SESSION[]). And output this data again when you display the form.

jinxed

7:52 am on Sep 21, 2011 (gmt 0)

10+ Year Member



Or post your form to the same page, collect the inputs that were submitted - do the validation checks and if they fail show them again on the original form (with an error message if the username already exists).

matthayzon89

2:39 pm on Sep 21, 2011 (gmt 0)

10+ Year Member



Thanks for the responses.

Which method is better do you guys think? Is SESSION commonly used tool?

I was trying to create a 'flag' variable in the processing script that I will somehow be able to use in the registration form (even though it is a separate file) but I do not think this is possible. Or is it?

So basically, if a user tries to sign up with a username that already exists than the flag variable turns from zero to one and then the form gets refreshed (using HTTP EQUIV tag) and then the 'value' attribute in the <input> tag gets changed to w/e the user typed in before. However, I feel like this isn't the best way to go about solving this type of problem.

rocknbil

4:18 pm on Sep 21, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I agree, it's not, generally redirection makes for more work than you need (IME.) I rarely do **any** redirecting at all. In your case, when the form refreshes, the user will have to re-enter all their values. You could use session variables to maintain them, but it's not needed (and if cookies are disabled, that won't work anyway.)

Structure your logic *something* like this.


if (isset($_POST['username']) and ! empty($_POST['username'])) {
$exists=0;
// CLEANSE IT FIRST
// select id from table where username=$username
($exists) = mysql_fetchrow_array;
// So $exists will be > 0
if ($exists > 0) {
output_form("user $username already exists, please choose another user name");
}
// The previous should output and exit, no need for an "else"
// insert into database here
// output success message
}
else { output_form(null); }


the function "output_form" will accept one optional parameter, the error. So on first load it has a default message, on error it will repopulate the form with submitted values.


function output_form($error=null) {
// there are better ways to do this - but populate
// post with empty values if they have not been set.
// If you have error reporting off, it will work without it
// BUT it will clog up your error log with every call
// to the script. It's just good practice to define
// variables even if they are not always used.
$vals = array ('username','pwd','yourname','email');
foreach ($vals as $val) {
$_POST[$val] = (isset($_POST[$val]))?$_POST[$val]:'';
}
$form = '
<form method="post" action="yourscript.php">
';
if ($error) {
$form .= '<p>There was an error in the data you
submitted: ' . $error . '</p><p>Please make the
appropriate corrections and try again.</p>';
}
else {
$form .= '<p>All fields are required. (or whatever....)</p>';
}
$form .= '
<p><label for="username">Username:</label>
<input type="text" name="username" id="username" value="' . $_POST['username'] . '"></p>
<p><label for="pwd">Password:</label>
<input type="password" name="pwd" id="pwd" value="' . $_POST['pwd'] . '"></p>
<p><label for="email">Email:</label>
<input type="text" name="email" id="email" value="' . $_POST['email'] . '"></p>
<p><label for="yourname">Your Name:</label>
<input type="text" name="yourname" id="yourname" value="' . $_POST['yourname'] . '"></p>
<p><input type="submit" value="Register"></p>
</form>
';
echo $form;
exit;
}


Of course, that is not working code (the function might be, but you need to output in a template) but gives you an idea.

EDIT: Taking that one step further with my "template" comment, you could do this. Instead of

echo $form;
exit;

do
return $form;

and change the program logic like so


if (isset($_POST['username']) and ! empty($_POST['username'])) {
$exists=0;
// CLEANSE IT FIRST
// select id from table where username=$username
($exists) = mysql_fetchrow_array;
// So $exists will be > 0
if ($exists > 0) {
$title = 'User Name Exists';
$content = output_form("user $username already exists, please choose another user name");
}
else {
// insert into database here
$title = 'Thank You For Registering';
$content = '<p>Your success message or whatever</p>';
}

}
else {
$title = 'Register';
$content =
output_form(null);
}
output_page($title,$content);


Where "output_page" accepts two parameters pretty much like the previous function (except they are required and have no null default) and opens your template, inserts the title and content, outputs and exits.

function output_page($title,$content) {
// Open template, store in $page, sub out $title and $content
echo $page;
exit;
}

matthayzon89

4:47 pm on Sep 21, 2011 (gmt 0)

10+ Year Member



Thank you for this very informative answer, I appreciate it:)
I will look it over closely and post back.

matthayzon89

7:37 pm on Sep 22, 2011 (gmt 0)

10+ Year Member



Hello,
I really appreciate your help. I kind of combined your logic with my original logic. However, I am getting a lot of 'undefined' variable notices even though I am checking whether a variable is set or not using the isset() function... is there any way to avoid this?

Obviously, if 'isset($_POST[username])' returns false than it hasn't been defined... grrr.

Thanks for any advice:D

penders

8:33 pm on Sep 22, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I am getting a lot of 'undefined' variable notices even though I am checking whether a variable is set or not using the isset() function... is there any way to avoid this?


If you are checking the variable with isset() before it is used then you shouldn't be getting any "undefined variable" notices on the variable you are testing.

if (isset($_POST[username])) {/*...*/}


However, this is likely to trigger a "Use of undefined constant username - assumed 'username' in ...", unless you have already defined a constant by that name. The word username should be quoted in this instance (it is a string).

matthayzon89

9:04 pm on Sep 22, 2011 (gmt 0)

10+ Year Member



YES! That did the trick! Thank you!

matthayzon89

12:38 am on Sep 23, 2011 (gmt 0)

10+ Year Member



Can someone please help me with my code below?! its a little long, its simply a registration form I am having a hard time being able to stop a user from submitting a partially filled out form... any ideas?


<?php
$form = '
<html>
<head>
<link rel="stylesheet" type="text/css" href="registrationstyle.css" />
<title>Zees - Registration Form</title>
</head>
<body>

<div id="container">
<p id="heading">Zee\'s Registration Form</p>
<form action = "http://localhost/www/databases/zeescreations/regis.php" method = "post" />
';

//create connection variale and connect to server
$conn = mysql_connect('localhost', 'root', '1likebeans');

//display error message if unable to connect
if(!$conn){
die('Unable to connect to server: ' . mysql_error());
}

//select database to connect to
mysql_select_db("zees", $conn);

//get all data from users table
$result = mysql_query("SELECT * FROM users");

//USER ID + VERIFY UNIQUITY
if(true){
if(!isset($_POST['usrid'])){
$form = $form . '
<div id="username">
Username:<br>
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="87px" />
<input type="text" name="usrid" />
</div>
';
}
else if(isset($_POST['usrid'])){
//get username from HTML form
$string1 = $_POST['usrid'];

$flag=1;
//make sure the username selected is unique by
//comparing it to all other usernames in the database
while($row = mysql_fetch_array($result)){
$string2 = $row['username'];
$flag=strcmp($string1,$string2);

if($flag==0){
$form = $form . '
<div id="username">
<div id="user_error">
<p><u>Error:</u> The username you have selected belongs to another user.
<br>Please try to select a unique username.
</p>
</div>
Username:<br>
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="87px" />
<input type="text" name="usrid" />
</div>
';
}
}
}
}
/*CHECK PASSWORD*/
if(true){
//DEFAULT => If NO passwords entered yet
if(!isset($_POST['password']) and !isset($_POST['confpassword'])){
$form = $form . '<div id="password">
Password: <input type="password" name="password" />
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="65px" />
Confirm Password: <input type="password" name="confpassword" />
</div>
';
}
//Check that passwords match
else{
$pass1 = $_POST['password'];
$pass2 = $_POST['confpassword'];

$password_match = strcmp($pass1,$pass2);

//passwords do NOT match
if($password_match!=0){
$form = $form . '
<div id="pass_error">
<p><u>Error:</u>
The passwords you entered do not match.
Please make sure both passwords match.
</p>
</div>
<div id="password" style="height:90px">
Password: <input type="password" name="password" />
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="65px" />
Confirm Password: <input type="password" name="confpassword" />
</div>
';
}
}
}
/* CHECK EMAIL MATCH */
if(true){
//DEFAULT E-mail DIV if NOTHING HAS BEEN ENTERED YET
if(!isset($_POST['email']) and !isset($_POST['confemail'])){
$form = $form . '
<div id="email">
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="9px" />
E-mail: <input type="text" name="email" />
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="84px" />
Confirm E-mail: <input type="text" name="confemail" />
</div>
';
}
else{
$mailOne = $_POST['email'];
$mailTwo = $_POST['confemail'];

$mail_match = strcmp($mailOne,$mailTwo);

//e-mails do not match
if($mail_match != 0){
$form = $form . '
<div id="email_error">
<p><u>Error:</u>
The e-mail addresses that you entered do not match.
Please make sure both e-mail addresses match.
</p>
</div>
<div id="email" style="height:90px">
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="9px" />
E-mail: <input type="text" name="email" />
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="80px" />
Confirm E-mail: <input type="text" name="confemail" />
</div>
';
}
}
}
$form = $form . '

<div id="hobbies">
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="4px" />
Hobbies (optional):
<br><img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="84px" />
<input type="text" name="hobbies" size="35" />
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="105px" />
Age: <input type="text" name="age" size="5" />
</div>

<center><input style="background-color:#333333" type="submit" value="Register" /></center>
</form>

</div>
</body>
</html>
';

if(isset($_POST['usrid']) and isset($_POST['password']) and isset($_POST['email']) and isset($_POST['age']) and isset($_POST['hobbies'])){
//Prepare query to add user to database
$query = "INSERT INTO users (username, password, email, age, hobbies)
VALUES ('$_POST[usrid]', '$_POST[password]', '$_POST[email]', '$_POST[age]', '$_POST[hobbies]')";

//submit query
mysql_query($query,$conn);

//close mysql connection
mysql_close($conn);
}
echo $form;
?>

rocknbil

4:27 pm on Sep 23, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, there are many things that could be done differently but the one that sticks out, that you have twice, is

if(true){

If what is true?

matthayzon89

2:17 am on Sep 24, 2011 (gmt 0)

10+ Year Member



Well, I constructed it that way because it makes sense to me logically. Conditionals with a true argument will always evaluate to true... so that 'if(true)' ONLY deals with the 'username' div, for example... the the next if(true) ONLY deals with 'password' div, etc.... you see my point?

I can easily remove that and still have it work, but that shouldn't keep the script from functioning properly, any other suggestions?

I appreciate all your feedback:)

penders

11:15 am on Sep 24, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You are checking for form submission errors and outputting an error the user will see, but you don't seem to be setting an 'error state' in your code that you can later check before actually processing the form. It looks like you are processing your form regardless of whether an error occurred during the validation stage.

One way to do this, to integrate with your current code, is to simply have an error count...

At the start of your script:
$errCount = 0;


When an error occurs:
//e-mails do not match  
if ($mail_match != 0) {
$errCount++;


Before processing the form:
if ($errCount == 0) { 
//Prepare query to add user to database
$query = "INSERT INTO users (username, password, email, age, hobbies) ...


Conditionals with a true argument will always evaluate to true... so that 'if(true)' ONLY deals with the 'username' div, for example... the the next if(true) ONLY deals with 'password' div, etc.... you see my point?


Errrm no?! Are you attempting to evaluate anything with if(true)? This doesn't evaluate to true, it is true! It will always execute, is completely superfluous and just unnecessarily complicates the code. ... Unless you are really wanting to check something... username, password, etc...?

matthayzon89

12:52 pm on Sep 24, 2011 (gmt 0)

10+ Year Member



Thank you for critique. I appreciate the advice. lol Exactly, if(true) IS true, I just put that in b/c it seemed to create some sort of logical structure for myself, it added it to help organize my logic rather than to follow good coding practice lol, but I guess I should take it out, it seems to serve NO purpose.

:)

Any other ideas how to keep users from submitting partially filled out forms? the error count idea will keep the forms from being processed and added to the SQL database, but it doesnt stop the users from submitting the page, and it doesn't redirect them BACK to the partially submitted page say "HEY! fill everything out man!"

... this is what im having trouble with...

Thank you! :D

penders

2:50 pm on Sep 24, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You can't actually prevent users from submitting partially filled out forms. PHP only kicks in when the form has been submitted. You can do some pre-validation with JavaScript and prevent the form from being submitted, but JavaScript can always be bypassed.

To 'redirect the user back to the partially filled out form' you need to write out the form, but for the values you substitute the POST vars the user has just submitted. I think rocknbil covers this in his post above... the output_form() function.

rocknbil

5:02 pm on Sep 26, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Re-read my first post a little closer, it discusses precisely that issue. Your form output, error responses, processing, and success response all needs to be within the context of the same script. Otherwise you have to resort to session variables and redirects, a bit too dependent on user settings (cookies) and session variables for my taste.

Yeah I wouldn't do a "count". Look at it this way: we start off assuming there are no errors. If there are errors, we're going to display them to the user in a string of some sort. So that string is a null value at the start.

$errors = null;

So if we encounter errors, we populate $errors with them.

if ($errors) { output_form($errors); }

Slightly modifying the previous example, we'd define what's required at the top:

$required_fields = Array (
'usrname' => 'User Login Name',
'fname' => 'First Name',
'email'=> 'Email Address'
);

We put it at the top because it may change at some point (add new field, etc.) On the left are the form field names, and the right "plain English" values so we don't have to say "the fname field is required."

Now it's time for a new function, check_input(). Our initial program logic could go like this:


if (isset($_POST['username']) and ! empty($_POST['username'])) {
$errors = check_input($required_fields);
if ($errors) { output_form($errors); }
// insert into database here
// output success message
}
else { output_form(null); }


So we move the initial exists thingie to our error check function. In this function we're passing the $required_fields as a param so we don't have to use program globals.


function check_input($fields) {
$exists=0;
$errors=null;
// First check required fields
foreach ($fields as $formname => $english) {
if (! isset($_POST[$formname) or (isset($_POST[$formname]) and empty($_POST[$formname]))) {
$errors .= "<li>The $english field is required to register.</li>";
}
}
// This only checks if there are no errors to this point.
// If you try to check it with $username empty, it will give a
// misleading message.
if (! $errors) {
// CLEANSE IT FIRST
// select id from table where username=$username
($exists) = mysql_fetchrow_array;
// So $exists will be > 0
if ($exists > 0) {
$errors .= "<li>user " . $_POST['username'] . "already exists, please choose another user name</li>";
}
return $errors;
}



And a slight change to output_form to pretty-fy our errors:

$form .= '<p>There was an error in the data you
submitted:</p><ul>' . $error . '</ul><p>Please make the
appropriate corrections and try again.</p>';

So you would potentially get

<ul>
<li>The User Login Name field is required to register.</li>
<li>The First Name field is required to register.</li>
<li>The Email Address field is required to register.</li>
</ul>

Which is much better than what I see a lot of, echo and exit on the first error:

The login field is required. Use your back button and fix it to register.*

This approach just checks for empty fields, and will require more work - for example, on the email you'd want a valid email address, maybe on user name you only want letters and numbers. But it's a decent start.


*Because I'm too lazy to code it so it's easy for you. :-)

matthayzon89

8:53 pm on Sep 26, 2011 (gmt 0)

10+ Year Member



I kind of constructed my registration form using your logic and advice @rocknbil, I appreciate you taking the time to put all that together.

However, I am new to php and a lot of your code and logic is a bit over my head.

Right now, the page can display itself but the error messages are not working, can anyone possibly clarify what I have forgotten to do or what I have done incorrectly? I was trying to work through it and I clarified a lot of different points that I didnt understand but I am still a bit stuck...


Thank in advance,
-Matt H.



<?php

//array containing what is required by the user
$required_fields = Array(
'userid' => 'User Login Name',
'password' => 'Password',
'email' => 'Email Address',
);


function check_input($fields){
$exists=0;
$errors=null;

foreach($fields as $forname => $english){
if(! isset($_POST[$forname]) or (isset($_POST[$forname]) and empty($_POST[$forname]))){
$errors = $errors . "<li>The $english field is required to register.</li>";
}
}
if(! $errors){
$exists = mysql_fetchrow_array;
if($exists > 0){
$errors = $errors . "<li> user " . $_POST['userid'] . "already existsm please choose a different username.</li>";
}
return $errors;
}
}

function output_form($error=null){
$vals = array ('userid', 'password', 'email', 'confemail', 'confpassword', 'hobbies', 'age');

foreach ($vals as $val) {
$_POST['$val'] = (isset($_POST['$val'])) ? $_POST['$val']:'';
}
$form = '
<html>
<head>
<link rel="stylesheet" type="text/css" href="registrationstyle.css" />
<title>Zees - Registration Form</title>
</head>
<body>

<div id="container">
<p id="heading">Zee\'s Registration Form</p>
<form action = "http://localhost/www/databases/zeescreations/regis2.php" method = "post" />
';

if ($error) {
$form .= '<p>There was an error in the data you
submitted: ' . $error . '</p><p>Please make the
appropriate corrections and try again.</p>';
}

$form = $form . '
<div id="username">
Username:<br>
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="87px" />
<input type="text" name="usrid" value="' . $_POST['usrid'] . '">
</div>

<div id="password">
Password: <input type="password" name="password" value="' .$_POST['username'].'">
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="65px" />
Confirm Password: <input type="password" name="confpassword">
</div>

<div id="email">
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="9px" />
E-mail: <input type="text" name="email" value="' .$_POST['email'].'">
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="84px" />
Confirm E-mail: <input type="text" name="confemail">
</div>


<div id="hobbies">
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="4px" />
Hobbies:
<br><img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="84px" />
<input type="text" name="hobbies" size="35">


<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="105px" />
Age: <input type="text" name="age" size="5">
</div>


<center><input style="background-color:#333333" type="submit" value="Register" /></center>
</form>
';


echo $form;
exit;

}

if(isset($_POST['username']) and !empty($_POST['username'])){
$errors = check_input($required_fields);
if($errors){
output_form($errors);
}

//** ADD USER TO DATABASE **//
//create connection variale and connect to server
$conn = mysql_connect('localhost', 'root', '1likebeans');

//display error message if unable to connect
if(!$conn){
die('Unable to connect to server: ' . mysql_error());
}

//select database to connect to
mysql_select_db("zees", $conn);

$query = "INSERT INTO users (username, password, email, age, hobbies)
VALUES ('$_POST[usrid]', '$_POST[password]', '$_POST[email]', '$_POST[age]', '$_POST[hobbies]')";

mysql_query($query,$conn); //submit query

//close mysql connection
mysql_close($conn);

//success message

}
else{
output_form(null);
}

?>

matthayzon89

4:20 am on Sep 27, 2011 (gmt 0)

10+ Year Member



to be more specific, how does the following 'foreach' loop run?
is my logic correct?
for each instance of the $fields array replace the $forname variable with the 'english' version of 'usrid' and 'fname'?


foreach($fields as $forname => $english){
if(! isset($_POST[$forname]) or (isset($_POST[$forname]) and empty($_POST[$forname]))){
$errors = $errors . "<li>The $english field is required to register.</li>";
}
}

ALSO,

how does the following code pick up on a usernames that already exist that is trying to be added to the database?

if (! $errors) {
// CLEANSE IT FIRST
// select id from table where username=$username
($exists) = mysql_fetchrow_array;
// So $exists will be > 0
if ($exists > 0) {
$errors .= "<li>user " . $_POST['username'] . "already exists, please choose another user name</li>";
}


...and last question, what does "CLEANSE IT" mean?

Thank you!

rocknbil

5:35 pm on Sep 27, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Mostly, it looks like it should fly . . .but only takes one typo to ruin your day. :-)

the page can display itself but the error messages are not working, can anyone possibly clarify what I have forgotten to do or what I have done incorrectly?


First note that the code I post is not "working code," it's all typed on the fly. But most of it seems correct. Just a few things catch my eye.

//localhost/www/databases/zeescreations/regis2.php

regis2.php is **this** script, correct, not some other file?

You have a mismatch of field names here:

$vals = array ('userid', 'password', 'email', 'confemail', 'confpassword', 'hobbies', 'age');

then

<input type="text" name="usrid" value="' . $_POST['usrid'] . '">

So when you go to do this,

if(isset($_POST['username']) and !empty($_POST['username'])){

if completely ignores the block, there's no "username".

I also see

<input type="password" name="password" value="' .$_POST['username'].'">

should be

<input type="password" name="password" value="' .$_POST['password'].'">

Unrelated, although this works,

$form = $form . '

the concatenation operator (dot) adds to the end of the value, like your previous line. When you do the previous you're completely replacing the contents of $form with what's in form PLUS this. It's no big deal, but all you need to do is keep adding to $form.

$form .= '

I would be wary of this:
$query = "INSERT INTO users (username, password, email, age, hobbies)
VALUES ('$_POST[usrid]', '$_POST[password]', '$_POST[email]', '$_POST[age]', '$_POST[hobbies]')";

Note how your POST keys are unquoted. There are conditions under which PHP may interpret these as constants, which they are not, and throw errors. Quoting gets confusing with mySQL; you need quote handling for PHP, but also need quoting for mySQL which is a different layer. Long story short, this will work:

$query = "INSERT INTO users (username, password, email, age, hobbies)
VALUES ('" . $_POST['usrid'] . "', '" . $_POST['password'] . "', '" . $_POST['email'] .
"', '" . $_POST['age'] . "', '" . $_POST['hobbies'] . "')";

Again, is it userid or usrid?

how does the following 'foreach' loop run?


OK an associative array is a key/value association. Look at this:

$required_fields = Array(
'userid' => 'User Login Name',
'password' => 'Password',
'email' => 'Email Address',
);
echo $required_fields['email'];

will echo 'Email Address'. It uses the symbol 'email' to access the plain english 'Email Address'. We do this because form field names get difficult to manage if we just use plain English words with spaces.

In Perl you can do this

print "$qs{'Email Address'};

but (pretty sure) you can't with PHP.

We pass this entire array to check_input and use the name "$fields" within the function. You can use any variable when you step through an array:

foreach($fields as $key => $value){
foreach($fields as $k => $v){

is my logic correct?


That part looks OK.

how does the following code pick up on a usernames that already exist that is trying to be added to the database?


It doesn't, it was a framework for example only, see comment about typing code on the fly above. :-) You need to do a select like any other DB query.


if (! $errors) {
// CLEANSE IT FIRST
// select id from table where username=$username
$query = "select id from table where username='" . $_POST['username'] . "'";
$result = mysql_query($query,$conn);
($exists) = mysql_fetchrow_array($result);
// So $exists will be > 0 IF it . . .exists
if ($exists > 0) {
$errors .= "<li>user " . $_POST['username'] . "already exists, please choose another user name</li>";
}


...and last question, what does "CLEANSE IT" mean?


Cleansing input is critical to programming. A malicious visitor can inject things into your forms to use email forms for spam, make modifications to your database . . . . this is too often an overlooked aspect of good programming. It's also a large topic, one you should immediately research after getting a working knowledge of scripting. The basic premise is "accept only what you want and throw everything else away." Input also should be prepared for insertion into a database like so:

$query = "INSERT INTO users (username, password, email, age, hobbies)
VALUES ('" .
mysql_real_escape_string($_POST['usrid']) . "', '" .
mysql_real_escape_string($_POST['password']) . "', '" .
mysql_real_escape_string($_POST['email']) . "', '" .
mysql_real_escape_string($_POST['age']) . "', '" .
mysql_real_escape_string($_POST['hobbies']) . "')";

mysql_real_escape_string [php.net]

But in itself, PHP mysql methods alone are not good enough for cleansing. Look into it after you get this working.

The last bit . . I would move your DB connection to the top so you only have to connect once for the username check and the insert. A good way to work is

// Configuration variables and things that may need to change over time first
// database connection
// any preprocessing stuff (not needed in your case)
// THE PROGRAM LOGIC HERE
// everything else below should be functions

matthayzon89

1:48 am on Sep 29, 2011 (gmt 0)

10+ Year Member



I appreciate all your responses rocknbil but honestly at this point I am super frustrated with this. I just can't seem to get it working properly. I have worked out all the errors, worked through your code logic and understand most of it. I re-arranged my code structure to have functions on the bottom, variables on top, etc... its seems like it should work completely fine, however, I am unable to get the errors to display, and I am unable to keep the users from submitting forms with a username, password, but NO e-mail for example. Or even A form with JUST a username...

Any advice as to what I am doing wrong?

<?php

//array containing what is required by the user
$required_fields = Array(
'userid' => 'User Login Name',
'password' => 'Password',
'email' => 'Email Address',
);

/**MAIN SCRIPT**/
//create connection variale and connect to server
$conn = mysql_connect('localhost', 'root', '1likebeans');

//display error message if unable to connect
if(!$conn){
die('Unable to connect to server: ' . mysql_error());
}

//select database to connect to
mysql_select_db("zees", $conn);


if(isset($_POST['userid']) and isset($_POST['password'])){
$errors = check_input($required_fields);

if($errors){
output_form($errors);
}

$query = "INSERT INTO users (username, password, email, age, hobbies)
VALUES ('$_POST[userid]', '$_POST[password]', '$_POST[email]', '$_POST[age]', '$_POST[hobbies]')";

mysql_query($query,$conn); //submit query

//close mysql connection
mysql_close($conn);
//success message
}
else{
output_form(null);
}

//This function checks that all the fields are filled out correctly
function check_input($fields){
$exists=0;
$errors=null;

foreach($fields as $forname => $english){
if(!isset($_POST['$forname'])){
$errors = $errors . "<li>The $english field is required to register.</li>";
}
if(! $errors){
//get all data from users table
$result = mysql_query("SELECT * FROM users");
$row = mysql_fetch_array($result);
$string1 = $row['username'];
$string2 = $_POST['userid'];
$exists = strcmp($string1,$string2);

if($exists == 0){
$errors = $errors . "<li> user " . $_POST['userid'] . "already exists please choose a different username.</li>";
}
return $errors;
}
}
}

function output_form($error=null){
$vals = array ('userid', 'password', 'email', 'confemail', 'confpassword', 'hobbies', 'age');

foreach ($vals as $val) {
$_POST['$val'] = (isset($_POST['$val'])) ? $_POST['$val']:'';
}
$form = '
<html>
<head>
<link rel="stylesheet" type="text/css" href="registrationstyle.css" />
<title>Zees - Registration Form</title>
</head>
<body>

<div id="container">
<p id="heading">Zee\'s Registration Form</p>
<form action = "http://localhost/www/databases/zeescreations/regis2.php" method = "post" />
';

if ($error) {
$form .= '<p>There was an error in the data you
submitted: ' . $error . '</p><p>Please make the
appropriate corrections and try again.</p>';
}
$form = $form . '
<div id="username">
Username:<br>
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="87px" />
<input type="text" name="userid">
</div>

<div id="password">
Password: <input type="password" name="password">
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="65px" />
Confirm Password: <input type="password" name="confpassword">
</div>

<div id="email">
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="9px" />
E-mail: <input type="text" name="email">
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="84px" />
Confirm E-mail: <input type="text" name="confemail">
</div>

<div id="hobbies">
<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="4px" />
Hobbies:
<br><img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="84px" />
<input type="text" name="hobbies" size="35">

<img src="http://i51.tinypic.com/jq52jc.jpg" height="0px" width="105px" />
Age: <input type="text" name="age" size="5">
</div>

<center><input style="background-color:#333333" type="submit" value="Register" /></center>
</form>
';


echo $form;
exit;

}

?>

rocknbil

6:22 pm on Sep 29, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



When in doubt, reduce to the least common denominator. Look:


function check_input($fields){
foreach($fields as $forname => $english){
if(!isset($_POST['$forname'])){
$errors . "<li>The $english field is required to register.</li>";
}
if(! $errors){
if($exists == 0){
$errors = $errors . "<li> user " . $_POST['userid'] . "already exists please choose a different username.</li>";
}
return $errors;
}
}
}


Can you see that? You have
foreach
--- if
--- if
---- if
---- return

Yoyu're returning inside the loop, and inside an if statement. Additionally the user ID check is supposed to come AFTER the foreach - you have it inside the foreach loop. You want

-- foreach
--- if
-- if
--- if
return

Move the return statement to just before the end of the function.


function check_input($fields){
foreach($fields as $forname => $english){
if(!isset($_POST['$forname'])){
$errors . "<li>The $english field is required to register.</li>";
}
}
if(! $errors){
if($exists == 0){
$errors = $errors . "<li> user " . $_POST['userid'] . "already exists please choose a different username.</li>";
}
}
return $errors;
}


Also, the check query is excessive and an example of doing in programming what you should be doing in the database layer. :-)

//get all data from users table (?) You don't need ALL. Just the record id.
// if it's there, user name exists.
$exists=0;
$query = "SELECT id FROM users where username='" . mysql_real_escape_string($_POST['userid']) . "'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$exists = $row[0];
if ($exists > 0) {
// conccatenate error
}