Jump to content

help with some code


leegreaves

Recommended Posts

ive customised some code to work with a registration page on my site but am coming across some problems and need some help with debugging it. The first problem ive come across is: im doing a check to see whether all fields have been entered and if not to inform that everything needs to be filled in BUT as soon as the page comes up the message comes straight up whether you have filled it or not. I know ill have other probs but would appreciate a little help sorting them out 1 by 1

 

<?php

define('DB_HOST', 'localhost');

define('DB_USER', 'tastscou_admin');

define('DB_PASSWORD', 'pentium');

define('DB_DATABASE', 'tastscou_members');

 

//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");

}

 

//define variables for fields

$username = mysql_real_escape_string(stripslashes($_POST['username']));

$password = mysql_real_escape_string(stripslashes($_POST['password']));

$email = mysql_real_escape_string(stripslashes($_POST['email']));

$sex = mysql_real_escape_string(stripslashes($_POST['sex']));

$dd = $_POST['day'];

$mm = $_POST['month'];

$yyyy = $_POST['year'];

$datestring = $yyyy . "-" . $mm . "-" .$dd;

$dob = mysql_real_escape_string(stripslashes($datestring));

 

//check if form has been submitted

if (isset($POST['submit']));

 

//check that no fields have been left blank

if (!$_POST['username'] | !$_POST['password'] | !$_POST['email'] | !$_POST['day'] | !$_POST['month'] | !$_POST['year'] )

{

die('You have not completed the form');

}

 

//check username is not already being used

if (!get_magic_quotes_gpc()) {

$_POST['username'] = addslashes($_POST['username']);

}

$usercheck = $_POST['username'];

$check = mysql_query("SELECT username FROM members WHERE username = '$usercheck'")

or die(mysql_error());

$check2 = mysql_num_rows($check);

 

//if that username exists return an error

if ($check2 != 0) {

die('Sorry, the username ' .$_POST['username']. ' is already in use');

}

 

//encrypt password to md5 checksum and add slashes if required

$_POST['password'] = md5($_POST['password']);

if (!get_magic_quotes_gpc()) {

$_POST['password'] = addslashes($_POST['password']);

$_POST['username'] = addslashes($_POST['username']);

}

 

//now add information to database

$insert = "INSERT INTO members (username, email, password, sex, dob) VALUES ($username, $email, $password, $sex, $dob)";

$add_member = mysql_query($insert);

?>

Link to comment
Share on other sites

please use [ code ] tags hereafter.

 

//check if form has been submitted
if (isset($POST['submit']));

you should be wrapping the code you only want processed with this IF statement:

if (isset ($_POST['submit'])) {
     //code goes here...
} //end IF statement;

next...

//check that no fields have been left blank
if (!$_POST['username'] | !$_POST['password'] | !$_POST['email'] | !$_POST['day'] | !$_POST['month'] | !$_POST['year'] )
{
die('You have not completed the form');
}

 

| should be || (|| means OR, and && means AND)

 

as well, sanitize ALL of your $_POST vars ($_GET and $_REQUEST for that matter, too) .. i noticed $mm, etc., are not being cleaned with mysql_real_escape_string() like the others.  i also noticed that you create a variable $username (for example), and then continue to use $_POST['username'] thereafter .. clean the variable, and don't go back to the original form .. i think you've assigned $_POST['username'] to three (3) or so different variable names.  waste of processing.

Link to comment
Share on other sites

thankyou for the pointer about the double || part so i can sort that part out...for the if isset part for the submit statement...that is a function on its own so should that really be put as:

 

if (isset ($_POST['submit'])) {

}

 

seeing as there is no code that needs to be wrapped in between the { and } or would it be better to wrap the next part of code in between these brackets ie:

 

if (isset($_POST['submit'])) {

 

//check that no fields have been left blank

if (!$_POST['username'] | !$_POST['password'] | !$_POST['email'] | !$_POST['day'] | !$_POST['month'] | !$_POST['year'] )

{

die('You have not completed the form');

}

 

};

Link to comment
Share on other sites

if (isset ($_POST['submit'])) {
     //code here...
}

 

in Layman's terms, this is like saying, "if the submit button has been pressed (has been set) on the form, or a field of some sort holding the name "submit" has been passed by the form, then process the code between the parenthesis.

 

you can then go onto to adding an 'else' clause afterwards to do something if the values has not been set/passed by the form.

 

to answer your last question, the entire script should be wrapped by that statement, unless you want that code executing everytime the page loads, even if the form hasn't been passed.  i doubt you want to have an INSERT statement run needlessly each time the page is run, correct?

 

it's a way of not allowing people to access the form processing code directly, like saying, "if you have reached this page without using the form, i will not process anything" .. you get the idea?

 

BTW, in order for this to work, you must have either a button (preferably), or a form field (ie., <input type="hidden" name="submit" value="foo" />) .. and that variable does not have to be "submit", it can be whatever you assign it, as long as it matches EXACTLY what is written in the form.  "submit" is just very descriptive and commonly used.

Link to comment
Share on other sites

i basically understand wot ur saying there ive corrected the || parts and also ive wrapped the 'submit' part with { and } the open starting after the isset for submit...the closing one comes after the other } just after the "blank field check" section. So if it does as it is supposed to do, IF the submit button is pressed and not all fields are entered correctly, then the error should occur, if not, it should pass through it:

 

//check if form has been submitted

if (isset($_POST['submit'] {

 

//check that no fields have been left blank

if (!$_POST['username'] || !$_POST['password'] || !$_POST['email'] || !$_POST['sex'] || !$_POST['day'] || !$_POST['month'] || !$_POST['year'] )

{

die('You have not completed the form');

}

};

 

Also you mentioned about the $mm $dd etc part in the variable defining, i did have a previous post linked to this code about a problem with dates and was suggested i do that.

 

http://www.phpfreaks.com/forums/index.php/topic,272660.0.html

Link to comment
Share on other sites

try this code, it uses switch() and generates errors based on what the user failed to submit;

 

didn't test, but i figured it'd give you something to play around with.

 

#check if form has been submitted;
if (isset ($_POST['submit']))
{
$errors[] = '';

define('DB_HOST', 'localhost');
define('DB_USER', 'tastscou_admin');
define('DB_PASSWORD', 'pentium');
define('DB_DATABASE', 'tastscou_members');

//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"); }

//check that no fields have been left blank
if (!isset ($_POST['username']))
{ $errors[] = 'Please enter a username.'; }
else
{ $username = mysql_real_escape_string(stripslashes($_POST['username'])); }

if (!isset ($_POST['password']))
{ $errors[] = 'Please enter a password.'; }
else
{ $password = md5 (mysql_real_escape_string(stripslashes($_POST['password']))); }

if (!isset ($_POST['email']))
{ $errors[] = 'Please enter an email address.'; }
else
{ $email = mysql_real_escape_string(stripslashes($_POST['email'])); }

if (!isset ($_POST['sex']))
{ $errors[] = 'Please enter your sex.'; }
else
{ $sex = mysql_real_escape_string(stripslashes($_POST['sex'])); }

if (!isset ($_POST['day']))
{ $errors[] = 'Please enter a day.'; }
else
{ $dd = mysql_real_escape_string(stripslashes($_POST['day'])); }

if (!isset ($_POST['month']))
{ $errors[] = 'Please enter a month.'; }
else
{ $mm = mysql_real_escape_string(stripslashes($_POST['month'])); }

if (!isset ($_POST['year']))
{ $errors[] = 'Please enter a year.'; }
else
{ $yyyy = mysql_real_escape_string(stripslashes($_POST['year'])); }

//check username is not already being used
$check = mysql_query("SELECT `username` FROM `members` WHERE `username` = '{$username}'") or die (mysql_error());

//if that username exists return an error
if (mysql_num_rows ($check) > 0)
{ $errors[] = 'Sorry, the username ' .$username. ' is already in use'; }

if (!is_array ($errors))
{ $do = 'insert'; }
else
{ $do = 'form'; }
}
else
{ $do = 'form'; }

switch ($do)
{
case form:
	//this next bit will display the
	//errors that were generated;
	if (is_array ($errors))
	{
		foreach ($errors as $error)
		{ echo $error.'<br />'; }
	}

	//now, display rest of your form here;
break;
case insert:
	#add information to database
	$insert = mysql_query ("INSERT INTO members (username, email, password, sex, dob) VALUES ({$username}, {$email}, {$password}, {$sex}, {$dob})");

	#make sure query worked;
	#if it did, you can redirect to a success page or something
	#or else, show an error;
	if ($insert)
	{ header ('Location: /success.php'); exit(0); }
	else
	{ echo 'Insert did not work:('; }
break;
default:
	//this is the default chunk of code
	//that will be displayed when user
	//first comes to page;  you can hard-code
	//or use include() files (cleaner) here;

	//put your form here;
break;
}

Link to comment
Share on other sites

whoop mrMracus ur a legend...now all i gotta do is workout where i need to put that...or which existing parts of my existing code need to go in after it!!! lmfao

it's pretty much plug-and-play .. meaning, where i commented 'add form here' and such, just insert your HTML form there (or PHP, whatever) .. to keep the code clean you can use include(), ie.

 

where i stated 'add your form here...', do this:

 

include ('path/to/form.php');

//create a file and name it form.php, then, put your form in there and make sure that 'path/to/' is the correct path to your form.php file.

 

your form will be something like this:

 

<form action="" method="post">
     <!-- input fields, etc., go here; -->
     <input type="submit" name="submit" value="Submit Form >>" />
</form>

 

right?  and...go.

Link to comment
Share on other sites

im guessing it would be better to include the body of the form using an include() condition then. if thats the case then thats ok with me i can just clean out the existing code that i added to the original form and go from there. thanks for the help and ill cross my fingers this is more successful

Link to comment
Share on other sites

ok im coming across an error here now...hmmm well ive called the new file you coded "form.php" in my registration.php form right at the VERY top before i get to my html code ive included the following:

 

include (form.php);

 

but im getting this error come up any ideas as to why (it appears on the page alongside the html and everything that shows up)

 

Warning: include() [function.include]: Failed opening 'formphp' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/tastscou/public_html/register.php on line 1

Link to comment
Share on other sites

i have one small question when im using the include() should i put it as such:

 

include(form.php); OR include('form.php')? cos ive noticed in the one ive entered the form and php phrases are in black text but the . (period) is in a blue coloured font

the parenthesis () are not actually needed when using include.

 

include 'form.php';

would work just the same as:

include ('form.php');

 

but yes, you need quotes around your filename.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.