# Mysql database and php



## randyrr (May 28, 2009)

Hey guys, i'm trying to set up a mysql database where an account status automatically default to inactive or '0'. When a user registers, it sends them an email for them to verify, after verification, the account become active or '1'.

nb.
1. I don't how to create it is inactive
2. Make active by user's when click 'link' in their email....

HELP PLEASEEEEEEEEE!!!!! 

thanks alot guys!!!


----------



## Redcore (Aug 14, 2007)

Do you have an account/login system already in place?


----------



## randyrr (May 28, 2009)

Yeah, I do, I can log in and log out of the system, but how do i ensure that the account is still inactive after registration?


----------



## Redcore (Aug 14, 2007)

Add a column to the database (user table) called "Active" or whatever you want as well as a column called "ActiveKey". When they first register, set the Active column to 0 and generate a random number to put in ActiveKey. Then send an email to them with a page to your site (verify.php or whatever) that has a form with an email box and a activation key box. Have that verify that the key matches the one in the database for that user. Alternatively you can include the key in the link in the email (ie: verify.php?key=023980823b093bjlkasdj388&[email protected]). Pretty simple system


----------



## randyrr (May 28, 2009)

thank you RedCore, cool, i understand the database part (moreless), but i'm not so good with the scripting part....what's the script to generate the random number and how do u out it in the "activationKey" column?

This is my php code that registers a user to the database, but how and where do i incorporate the code to generate the random key so they can verify?

Hey btw, that a million for even looking at this!!

```
<?php
//session_start();
// Connect to the server			
		$db = mysql_connect("localhost", "username", "password") 
		or die("testing connection");
		echo ("connected");		

	

// connect to the db
		mysql_select_db("dbname", $db) or
		die("cannot connect to the database");
		echo(" <br />Connection  successful<br/>");

	$formstudent_fname = $_POST['student_fname'];
	echo "</br>"; 
	$formstudent_lname = $_POST['student_lname'];
	echo "</br>"; 
	$formstudent_address_no = $_POST['student_address_no'];
	echo "</br>"; 
	$formstudent_street_name = $_POST['student_street_name'];
	echo "</br>"; 
	$formstudent_phone = $_POST['student_phone'];
	echo "</br>"; 
	$formstudent_email = $_POST['student_email'];
	echo "</br>"; 
	$formstudent_username = $_POST['student_username'];
	echo "</br>"; 
	$formstudent_password = $_POST['student_password'];
	echo "</br>"; 
	$formstudent_password2 = $_POST['student_password2'];
	echo "</br>";

			

//check to see if the name exists in the current event table
$query = "SELECT student_username FROM student WHERE student_username = '$formstudent_username' ";
$results = mysql_query($query);

// this makes sure both passwords entered match
//if ($_POST['student_password'] != $_POST['student_password2']); {
//die('Your passwords did not match. ');
//}

// here we encrypt the password and add slashes if needed
$_POST['password'] = (md5($_POST['password']));
if (!get_magic_quotes_gpc()) {
$_POST['password'] = addslashes($_POST['password']);
$_POST['username'] = addslashes($_POST['username']);
}	


if (!mysql_num_rows($results) == 0) {	 //exists within the table
echo "We're sorry, but this username is already taken, please try another username <a href=register.html> Click this link to register again</a>";
//*** output the list of names within the database
mysql_close();

//possible return FALSE?
//pop up box asking if user wishes to update the information
//yes update
//no cancel

} else { //does not exist within this table, continue & add to table
$results = "INSERT INTO student (student_fname,student_lname,student_address_no,student_street_name,student_phone,student_email,student_username,student_password,student_password2,active,activekey) VALUES ('$formstudent_fname','$formstudent_lname','$formstudent_address_no','$formstudent_street_name','$formstudent_phone','$formstudent_email','$formstudent_username','$formstudent_password','$formstudent_password2',0,'RAND(0)')";


echo "<h2>Thank you, $formstudent_fname, for registering with us, you may <a href=../login.html>login</a>now.<br /></h2>";


if (!mysql_query($results)) {
echo "<h1>We were unable to insert this record.<br />The error was: </h1>" .

mysql_error();
mysql_close();
}
}
?>
```


----------



## FredT (Nov 16, 2007)

First, I don't think you need the ! on this line:

```
if (!mysql_num_rows($results) == 0) {	 //exists within the table
```
For your original problem...

```
$random_key = uniqid();     //uniqid() generates a random string
```
Then put it in...

```
$results = "INSERT INTO student (student_fname,student_lname,student_address_no,student_street_name,student_phone,student_email,student_username,student_password,student_password2,active,activekey) VALUES ('$formstudent_fname','$formstudent_lname','$formstudent_address_no','$formstudent_street_name','$formstudent_phone','$formstudent_email','$formstudent_username','$formstudent_password','$formstudent_password2',0,'$random_key')";
```


----------



## randyrr (May 28, 2009)

It Works!!!! Thank you FredT!

i'm have to now use Argosoft Mail server together with MS Outlook for the purpose of this school project. I, however, need to send an email to the subscriber's address in so they could activate their's accounts.

I know it's beyond this thread, but do you know how to do that perhaps?

Thanks again buddy!!!
[[--merged from double-posting--]]
i have some sample php code i.e

```
<?php
//define the receiver of the email
$to = '[email protected]';
//define the subject of the email
$subject = 'Activation email'; 
//define the message to be sent. Each line should be separated with \n
$message = "Hello World!\n\nThis is my first mail."; 
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: [email protected]\r\nReply-To: [email][email protected][/email]";
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent to $to" : "Mail failed";
?>
```
I'm a bit confused where 'localhost' comes in, because i think it's supposed to be done without actual internet access.....

_[[Moderator's Note: please do not double-post. You may ask a member of staff to either edit your original post or merge consecutive posts. Thank you. —dm01]]_​


----------



## Redcore (Aug 14, 2007)

The server needs mail enabled and Internet access in order to send out emails. It seems a little odd that they want you do it without Internet access but want authentication. Or maybe that's just your own feature. What you could do in that case is just make it look like it just sent an email but instead of doing that, it writes the verify URL to a text file (with the activation code, obviously) and you just copy that into your browser. You can explain that it's the same thing the email would have had, but you're doing this as a localized example.


PS: please use the PHP tags for your PHP code


----------



## randyrr (May 28, 2009)

well, we're supposed to use Argosoft and MS Outlook together on localhost, does this make sense? (the localhost part?)..


----------



## Redcore (Aug 14, 2007)

Hmm...I've never done that sort of thing. Probably a question for the server guys in the Windows Server section...


----------



## randyrr (May 28, 2009)

or...ohhk, thank buddy!!! I have some more questions but i need to do some more work first...


----------



## randyrr (May 28, 2009)

hey, i wanna set up php sessions on a few pages, at the top of each page, i have

<?php
session_start();

if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: login.php");
}

?>

After a while i started getting a message saying, "This page has a redirect loop".

Now, i can logically assume that the sessions are not scripted properly,

PLZ HELP!!!

Let's say i have 6 pages (index.php being the home page)

1. Index.php
2. Courses.php
3. Personalize.php
4. Search.php
5. Upload.php
6. Welcome.php

I want to redirect anyone who is not logged in, back to the login.php page,

So what i did was put that piece of code at the top of each page...

Please correct me....


Randy


----------



## Gorge (Nov 10, 2008)

a few hints:


*security issue:*
you should always escape user input, i.e.

```
$query = "SELECT student_username FROM student WHERE student_username = '$formstudent_username' ";
```
 should become

```
$query = "SELECT student_username FROM student WHERE student_username = '"
	. mysql_escape_string($formstudent_username). "'";
```
If you don´t, your site will be open to sql injections.

*catching errors*
query submissions should be checked for success, so after

```
$results = mysql_query($query);
```
 you should add

```
if (!$results) die('db query failed');
```
(btw: mysql_num_rows($results) would return -1 in that case)

*magic quotes* (fortunately they will remove them in php version 6):
If you´re not sure about the server settings, you should always check them. So

```
$formstudent_fname = $_POST['student_fname'];
[...]
$formstudent_password2 = $_POST['student_password2'];
echo "</br>";
```
 etc. would be safe to move to any server with this:


```
$fields = array (
	'student_fname', 'student_lname', 'student_address_no',
	'student_street_name', 'student_phone', 'student_email',
	'student_username', 'student_password', 'student_password2'
);
$magic_quotes_gpc = str_cmp(php_version(), '6')<0 && ini_get('magic_quotes_gpc');
if ($magic_quotes_gpc)
	foreach ($fields as $key) ${'form'.$key} = strip_slashes($_POST[$key]);
else
	foreach ($fields as $key) ${'form'.$key} = $_POST[$key];
```

I´m not sure what sense these "echo '</br>';" make, but you should turn them into proper HTML (echo '<br>' or XHTML (echo '<br />' - or remove them altogether.
If you´re sure you want to keep them, just append

```
echo str_repeat('<br />', count($fields));
```
 to the magic quote stuff.


----------



## Redcore (Aug 14, 2007)

I've asked a few times - PLEASE use the PHP tags to make it easier to read.

As far as your code:

```
<?php
session_start();

if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: login.php");
}

?>
```
That logic seems a bit funky. It's basically saying if LOGIN is not set and LOGIN does not equal '' (nothing)...go to 'login.php'.

Should just be simple:

```
<?php
session_start();

if(empty($_SESSION['login'])) {
header ("Location: login.php");
}

?>
```


----------



## randyrr (May 28, 2009)

Ohhhhh.......

I'm sorry RedCore, you won't believe I didn't know how to do that....LOL..

I'm not accustom to 'forums' and their rules u know?.... 


Randyrr


----------



## Redcore (Aug 14, 2007)

Around your code you just put: [ PHP ] code [ / PHP ]

(without the spaces)


----------



## randyrr (May 28, 2009)

okk, thanks so i correct to say that i simply put that code on top every page that i watn top protect?


----------



## Redcore (Aug 14, 2007)

Yeah. It should provide basic authentication. It depends how important the data you're trying to protect is. You could do implement a session token system, authenticating that token on each page call. There are quite a few articles out there on this sort of stuff when you Google it.


----------



## randyrr (May 28, 2009)

Hey Redcore, 

Here's what happening now, whenever i log in and go to welcome page, if i click on a page with the session code on it, it's going back to the login.php (somehow....Therefore, i still cannot access protected pages.... 

Can you advise me what can this problem?



```
<?php
session_start(); 

	if(empty($_SESSION['login'])) { 
	header ("Location: login.php"); 
	} 
?>
```


----------



## Redcore (Aug 14, 2007)

I didn't see where you set this session variable in your login code. Could you post that?


----------



## randyrr (May 28, 2009)

This is my validateuser page that process the from from the login page (This works)


```
<?php

?>
```
<html>
<head>
<title></title>
<link rel="stylesheet" href="../css/style2.css" type="text/css" charset="utf-8" />
</head>
<body bgcolor="#694545;">

```
<?php


function getData(){};

// Connect to the server			
		$db = mysql_connect("localhost", "root", "test") 
		or die("testing connection");
		echo ("connected");		

	

// connect to the db
		mysql_select_db("educational", $db) or
		die("cannot connect to the database");
		echo(" <br />Connection  successful<br/>");



if (isset($_POST['submit'])) { // if form has been submitted

// makes sure they filled it in
if(!$_POST['student_username'] | !$_POST['student_password']) {
die('Error! </br> Required Fields are incomplete!</br >You did not fill in a required field!</br>
	Click here to <a href="login.php">go back</a>.');
}

}

if($_SERVER['REQUEST_METHOD']=="POST"){

$qer="select * from student where student_username='".$_POST['student_username']."' and student_password='".$_POST['student_password']."'";
$res=mysql_query($qer);
$num=mysql_num_rows($res);
if($num==0)
{
$msg=1;
}
else if($num==1)
{
session_unregister("student_username");
session_register("student_username");
$_SESSION['student_username']=$_POST['student_username'];

session_unregister("student_id");
session_register("student_id");
$_SESSION['student_id']=getData("student","student_id","student_username='".$_POST['student_username']."' and student_password='".$_POST['student_password']."'");

echo'<script language="javascript"></script>';
echo'<script language="javascript">window.location.href="welcome.php";</script>';
}
}


?>

<!-- prints invalid user: -->

 <?php if(!empty($msg) && $msg==1)

	{echo "Oops! Login error, please check you username or password or click <a href=login.php> here </a> to try logging in again.";}
?>
</body>
</html>

<?php
?>
```


However, when i set the session below, my guess is that it parses false and goes back to the validateuser(login) page.....

When i removed the session details, only then i can go to the welcome page....
I can't seem to figure out why the 'session empty' is saying true, even though the login credentials are fine.... 


This is my Welcome Page....




```
<?php 
session_start();  

    if(empty($_SESSION['login'])) {  
    header ("Location: login.php");  
    } 	

?>

<html>
<head>

<title>AEW | WELCOME</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link href="../style.css" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="../js/form.js"></script>


</head>

<body>

<div id="container">

<div id="banner"><h1>Adult Educational Website</h1></div>

<div id="navcontainer">

			<ul id="navlist">                           
				<li id="active"><a id="current" href="http://www.techsupportforum.com/design-forum/index.html">Homepage</a></li>
				<li><a href="http://www.techsupportforum.com/design-forum/upload.html">Upload Assignments</a></li>
				<li><a href="courses.php">View All Courses</a></li>
				<li><a href="http://www.techsupportforum.com/design-forum/contact_us.html">Contact Us</a></li>

			</ul>
</div>

<div class="intro">

<h2>Welcome to <span style="font-weight:bold; color:#069;">I-Edu</span></h2>

<p><img class="imgleft" src="http://www.techsupportforum.com/design-forum/img/orb.png" alt="icon" title="icon" /> <strong>This is the First website of its kind, here you can upload your assignments.</strong> </p>
<p>» <a href="#">Read more</a></p> </div>

<div class="separator"></div>

<div class="intro2"><h2>Personalize</h2>
<p><img class="imgleft" src="http://www.techsupportforum.com/design-forum/img/orb.png" alt="icon" title="icon" /> Please register to gain free access to thousands of journals and other resources... </p>
<p>» <a href="#">Read more</a> </p></div>

<div class="intro3"><h2>Uploading Assigments</h2>
<p><img class="imgleft" src="http://www.techsupportforum.com/design-forum/img/orb.png" alt="icon" title="icon" /> We are a small school located in Central London...</p>
<p>» <a href="#">Read more</a> </p></div>

<div style="clear:both;"></div>

<div id="sidebar">

<h1>News</h1>

<p> Earn your degree online, <br />coming soon !!!</p>


<h1>Links </h1>

			<ul>
				<li><a href="#">Snapp Happy</a></li>
				<li><a href="#" title="The Open Design Community">TODC</a></li>
				<li><a href="#">Andreas Viklund</a></li>
				<li><a href="#">James Koster</a>  </li>
				<li><a href="#">OSWD</a></li>
				<li><a href="#"> CSS play </a></li>
				<li><a href="#" title="CSS menus">Listamatic </a></li>
			</ul>

</div>

<div id="content">

  
  <table style="bordercolor:#FFFFFF; bordercolorlight:#C0C0C0; bordercolordark:#808080; bgcolor:#FFFFFF" border="0" width="70%" cellspacing="0" cellpadding="0">
	<tr>
	<td style="bordercolor:#000000; bordercolorlight:#000000; bordercolordark:#000000; bgcolor:#000000">
		
<?php
	
	print "Welcome, {$_SESSION['student_fname']} {$_SESSION['student_lname']}!";
	print  "and thanks for registering, you can feel free to enjoy any content on this site.!!"


		?>

]		<br /><br />Regards,<br />The University Web Team
	



					</td>
					</tr>
					</table>

    
</div>

<div id="footer">

<a href="#">homepage</a> | <a href="mailto:">contact</a> | <a href="http://validator.w3.org/check?uri=referer">html</a> | <a href="http://jigsaw.w3.org/css-validator">css</a> |  © 2007 
</div>

</div>
</body>
</html>

<?php

?>
```
_[[Moderator's Note: please use


PHP:


 and [HTML] as Redcore suggested.]][/RIGHT][/I]

_


----------



## Redcore (Aug 14, 2007)

It doesn't appear that you're setting the LOGIN session variable, but rather just the "student_id" session variable.

PS in PHP5 you don't need to register session variables


----------



## randyrr (May 28, 2009)

lol...waw, now i'm more at a loss....lol
Do mean this line of code?


```
session_unregister("student_username"); 
session_register("student_username"); 
$_SESSION['student_username']=$_POST['student_username']; 

session_unregister("student_id"); 
session_register("student_id"); 
$_SESSION['student_id']=getData("student","student_id","student_username='".$_POST['student_username']."' and student_password='".$_POST['student_password']."'"); 

echo'<script language="javascript"></script>'; 
echo'<script language="javascript">window.location.href="welcome.php";</script>'; 
} 
} 

?>
```

If so, how do I then integrate the Login session variable??...i'm stumped...


----------



## Redcore (Aug 14, 2007)

In your validation you're trying to see if the session variable "login" exists - if you don't set it, it will always send it back to the login page.

Your code should *theoretically* look more like this:


```
<?php
$_SESSION['student_username']=$_POST['student_username']; 

$_SESSION['student_id']=getData("student","student_id","student_username='".$_POST['student_username']."' and student_password='".$_POST['student_password']."'"); 
$_SESSION['login'] = 'set';

echo'<script language="javascript"></script>'; 
echo'<script language="javascript">window.location.href="welcome.php";</script>'; 
} 
} 

?>
```
Alternatively you can set up the validation script to check for the 'student_id' session variable instead of 'login' ...


```
<?php 
session_start();  

    if(empty($_SESSION['student_id'])) {  
    header ("Location: login.php");  
    }     

?>
```
Is that more clear? :smile:


----------



## randyrr (May 28, 2009)

Crystal clear Redcore!!! but...lol..i'm still having the same problem, with both examples.....all 

after making validation changes, all i have atop the protected page is 


```
<?php 
session_start(); 

if(empty($_SESSION['student_id'])) { 
header ("Location: login.php"); 
} 

?>
```


----------



## Redcore (Aug 14, 2007)

Hmm. Works for me. Do you have "session_start();" at the top of your login page?


----------



## randyrr (May 28, 2009)

yeah i do... see below my login page (validateuser.php)


```
<?php
session_start();


function getData(){};

// Connect to the server			
		$db = mysql_connect("localhost", "un", "pw") 
		or die("testing connection");
		echo ("connected");		

	

// connect to the db
		mysql_select_db("educational", $db) or
		die("cannot connect to the database");
		echo(" <br />Connection  successful<br/>");



if (isset($_POST['submit'])) { // if form has been submitted

// makes sure they filled it in
if(!$_POST['student_username'] | !$_POST['student_password']) {
die('Error! </br> Required Fields are incomplete!</br >You did not fill in a required field!</br>
	Click here to <a href="http://www.techsupportforum.com/design-forum/login.html">go back</a>.');
}

}

if($_SERVER['REQUEST_METHOD']=="POST"){

$qer="select * from student where student_username='".$_POST['student_username']."' and student_password='".$_POST['student_password']."'";
$res=mysql_query($qer);
$num=mysql_num_rows($res);
if($num==0)
{
$msg=1;
}
else if($num==1)
{


$_SESSION['student_username']=$_POST['student_username'];  

$_SESSION['student_id']=getData("student","student_id","student_username='".$_POST['student_username']."' and student_password='".$_POST['student_password']."'");  
$_SESSION['login'] = 'set'; 

echo'<script language="javascript"></script>';  
echo'<script language="javascript">window.location.href="welcome.php";</script>';  


}
}


?>

<!-- prints invalid user: -->

 <?php if(!empty($msg) && $msg==1)

	{echo "Oops! Login error, please check you username or password or click <a href=login.php> here </a> to try logging in again.";}
?>
```
once i select another page, e.g page2.html that has :

```
<?php  
session_start();  

if(empty($_SESSION['student_id'])) {  
header ("Location: login.html");  
}  

?>
```
it goes back to login.html page


----------



## Redcore (Aug 14, 2007)

Let's go through your login script. It seems to have a lot of security holes and various practices I'm unclear about.

A) Why is your "getData" function empty? Doesn't seem to actually do anything.

B) Never put non-sanitized user-defined variables into anything, especially database queries. Do that by using mysqli_real_escape_string

```
$student_username = mysqli_real_escape_string( $_POST['student_username'] );
```
C) Always encrypt passwords and never put cleartext passwords anywhere. Use MD5 to encrypt with a salt (adding some extra characters after the password is input).
Example:

```
$original_password = 'password02' 
/* -> our user is naive and thinks this is secure! many hackers have a 
huge table with thousands/millions of encrypted password with their 
correlated cleartext unencrypted password. we need to add some text 
to force a password to encrypt differently than it normally would...*/
$original_password = $original_password . '#random_89827$';
// -> NOW encrypt...
$original_password = MD5($original_password);
```
D) I'm not sure what you're trying to store in the 'student_id' SESSION variable. Since the "getData" function is empty (aka, useless) that variable is not storing anything. Nothing is getting stored in the 'student_id' SESSION variable, so it will always come up empty in subsequent validations.


----------



## randyrr (May 28, 2009)

sigh....ok..Thanks alot Redcore!!

Maybe i should've mentioned that i'm a newbie and don't really know how to fix the problem, so i'd save alot of time...

Please bear with me...


----------



## Redcore (Aug 14, 2007)

Hah, I gathered that you're new - everyone has to start somewhere  I'm always totally happy to help so long as the person I'm helping doesn't depend on me - meaning they try to do it themselves a few times before asking.


----------



## randyrr (May 28, 2009)

Super cool man!!! Thanks!!! 

Hey Redcore, I've come up with this, but it still doesn't work... 


```
<?php session_start();

if (isset($_GET['logout']))
{
	$_SESSION = array();
	if ($_COOKIE[session_name()])
	{	setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();

}
if (isset($_POST['username']))
{
$username = htmlentities($_POST['username']);
$password = htmlentities($_POST['password']);

if ( $username == '$_POST["student_phone"]' and $password == '$_POST["student_phone"]')
{
		$_SESSION['username'] = $username;
echo 'login successful <br />';
echo 'Welcome,'. $username;
}
else
	{
		echo '<span style=color: red />Login Failed<br />';
		echo $username. ', does not exist';
	}


//convert the field values to simple variables 

//add slashes to the username and md5() the password 
$username = addslashes($_POST['username']); 
$password = md5($_POST['password']); 


//set the database connection variables 

$dbHost = "localhost"; 
$dbUser = "root"; 
$dbPass = "test"; 
$dbDatabase = "educational"; 

//connet to the database 

$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database."); 

mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database."); 

$result=mysql_query("select * from users where username='$user' AND password='$pass'", $db); 

//check that at least one row was returned 

$rowCheck = mysql_num_rows($result); 
if($rowCheck > 0){ 
while($row = mysql_fetch_array($result)){ 

  //start the session and register a variable 

  session_start(); 
  session_register('username'); 

  //successful login code will go here... 
  echo 'Success!'; 

  //we will redirect the user to another page where we will make sure they're logged in 
  header( "Location: checkLogin.php" ); 

  } 

  } 
  else { 

  //if nothing is returned by the query, unsuccessful login code goes here... 

  echo '<br />Incorrect login name or password. Please try again.'; 
  } 
  } 
  ?>
```


```
<html>
<head>
<title>TEst</title>
<!-- <link rel="stylesheet" href="../style.css" type="text/css" charset="utf-8" />	-->
</head>
```
i have test data that i manually put into the db, but is says the "username" doesn't exist

_[[Moderator's Note: please do not double-post. Ask a member of staff to edit your original post or merge consecutive postings. Thank you. —dm01]]_​


----------



## Redcore (Aug 14, 2007)

So long as "<username> doesn't exist" is indeed the error you're receiving, you hard coded that and this is what it's stumbling on:


```
if ( $username == '$_POST["student_phone"]  ' and $password == '$_POST["student_phone"]  ')
        {
        $_SESSION['username'] = $username;
        echo 'login successful <br />';
        echo 'Welcome,'. $username;
        }        else        {
        echo '<span style=color: red />Login Failed<br />';
        echo $username. ', does not exist';
        }
```
It looks like you're trying to validate the posted username/password but I'm not sure why you're validating this way.

A few more notes:

"htmlentities()" doesn't do a whole lot for you in this scenario
Use "mysql_real_escape_string()" to prevent SQL injection
It's typically best to leave variables outside of quotes. Putting variables in quotes seem to cause problems at times, I don't know why. Anyways, it's more difficult to see that it's a variable because it's formatted as a string in all text editors.
I'm a self-confessed "format Nazi" - but I really do believe that good consistent formatting is a keystone of good development. It'll help you work through the program flow a lot faster, you see where you're in a loop and what loop you're in much easier. 
Any time you echo or print anything to the screen, you lose the ability to use "header()" 
When you're just doing a basic row check, the data you pull back is not important. Therefore, instead of selecting all ("SELECT * FROM ... ") just select a small field to minimize memory usage (which is probably minimal when you have a small table, but it's a good practice).
As of PHP5, you no longer need to manually register each session variable. Just the act of setting a session variable (ie: "$_SESSION['variablename'] = 'test'; ") automatically registers the variable in the same way that you don't have to register normal variables. Cool, huh? 
I only reformatted your code - you'll need to set the cookie (after the session variable is created) and you should look into fixing the logout portion yourself before I help with it (I know, lame - but it's in the effort to make sure you learn! :wink. 


I reworked most of your code (in the login section) so try this out...

```
<?php 
session_start();

if(isset($_GET['logout']))
	{
	$_SESSION = array();
	if ($_COOKIE[session_name()])
		{
		setcookie(session_name(), '', time()-42000, '/');
		}
	session_destroy();
	}
	
if(isset($_POST['username']))
	{
	// convert the field values to simple variables 
	// add slashes to the username and md5() the password 
	// escape any SQL injection with mysql_real_escape_string
	$username = mysql_real_escape_string($_POST['username']);
	$username = addslashes($_POST['username']);
	$password = md5($_POST['password']);
	
	//set the database connection variables 
	$dbHost = "localhost"; 
	$dbUser = "root"; 
	$dbPass = "test"; 
	$dbDatabase = "educational";
	
	//connect to the database 
	$db = mysql_connect($dbHost, $dbUser, $dbPass) or die ("Error connecting to database."); 
	mysql_select_db($dbDatabase, $db) or die ("Couldn't select the database."); 
	
	// run the query - only pull "username" field because it's useless to us, so there's no need to pull back everything
	// -> we just want to count the number of rows pulled as a result of the query below.
	$result=mysql_query("SELECT username FROM users WHERE username='".$username."' AND password='".$password."'", $db); 
	
	//check that at least one row was returned 
	$rowCheck = mysql_num_rows($result); 
	if($rowCheck > 0)
		{
		$_SESSION['username'] = $username;
		
		//we will redirect the user to another page where we will make sure they're logged in
		header( "Location: checkLogin.php" );
		}	else	{
		//if nothing is returned by the query, unsuccessful login code goes here...
		echo '<br />Incorrect login name or password. Please try again.';
		}
	}
?>
```


----------



## randyrr (May 28, 2009)

Hey RedCore, I've managed to get through with the PHP sessions, but i just wanna say thanks man!!!!

I have a simpler problem though?

i'm trying to store 'date and time' info in my database,

My code so far is

From HTML Form


Date Required:<select size="1" name="Date" value="dd">
<option selected>day</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option>24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
</select>

<select size="1" value="mm">
<option selected>month</option>
<option>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>

<select size="1" value="yyyy">
<option selected>year</option>
<option>2009</option>
<option>2010</option>
</select>

Time Required: 

<select name="Time" size="1">
<option value="HH">hh</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>

<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>

<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>

<select name="Time" size="1">
<option value="MM">mm</option>
<option value="00">00</option>

<option value="05">05</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>

<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
<option value="55">55</option>
</select>

<select name="Time" size="1">
<option selected>am/pm</option>
<option value="AM">AM</option>
<option value="PM">PM</option>
</select> 

in my php form i have


```
<?php
$formdate = $_POST['date'];
echo "</br>";
$formtime = $_POST['time'];
echo "</br>";
?>
```
Obviously i know that u realise i can't pass any values but even when it does pass, i cannot store it in mysql because mysql accepts a 'dd-mm-yyyy' format etc...

The question however is,

How can get my html form to store all selected options as ONE date field, to insert into my database (dd-mm-yyyy) ???

I'm stumped..

Thanks alot for ur time..


Randyrr


----------



## Redcore (Aug 14, 2007)

You COULD try to use jQuery UI and one of these datetime picker libraries...
http://milesich.com/timepicker/
http://blogs.uct.ac.za/blog/lovemores-world/2009/02/25/an-effective-jquery-date-time-picker

But if you want to do it manually, you'd take all those values, pass them individually, and "paste" them together with PHP:


```
<?php
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];

$date = $year . '-' . $month . '-' . $day;
?>
```
Personally, I go the jQuery route. They have a date picker that is built into their library, the two above are external (to include time functionality) and I haven't yet tried them.


----------



## randyrr (May 28, 2009)

THank you so much Redcore,

I got through with the Date/Time thingy!!!!

I'm trying to Update a specific row in mysql when the user selects a button from a form in PHP

Here goes:


```
echo "<table border='1' cellspacing='1' bgcolor='black'>
	<tr color='FFDDEECC'>
	<th>Job ID</th>
	<th>Job Location</th>
	<th>Job Status</th>
	</tr>";
  
  echo "<tr>";
  echo "<td>" . $row['job_id'] . "</td> ";
  echo "<td>" . $row['Job_loc'] . "</td> ";
  echo "<td>" . $row['job_status'] . "</td> ";
  echo "<td><form name='getjob' method='post' action='update.php'>
  <input type='submit' name='job_id' id='job_id' value='Pickup Job'>
  </form></td>";
  
  echo "</tr></table>";
```
when the user selects "Pickup Job"

i'm trying to pass the job_id so only that row will be updated....

now here's the rest


```
<?php

//db connection etc...

$formjob_id = $_POST['job_id'];
echo "</br>";


	$query ="UPDATE jobs SET job_status=0 WHERE job_status=1 AND job_id='$job_id' " or die ("cannot Pickup Job");
			
							
if ($formjob_id != 0) {
die('Sorry, '.$_POST['user'].' this booking has been picked up already by another driver.');
}

else{
echo"Job $job_id updated<br />";
}		

?>
```

my problem is that nothing is parsed at all (even is if say '$formjob_id' or simply '$job_id').....what do u think could be the problem ??


Thanks again,

randyrr


----------



## Redcore (Aug 14, 2007)

There needs to be a form element to pass it to...


```
echo "<table border='1' cellspacing='1' bgcolor='black'>
    <tr color='FFDDEECC'>
    <th>Job ID</th>
    <th>Job Location</th>
    <th>Job Status</th>
    </tr>";
  
  echo "<tr>";
  echo "<td>" . $row['job_id'] . "</td> ";
  echo "<td>" . $row['Job_loc'] . "</td> ";
  echo "<td>" . $row['job_status'] . "</td> ";
  echo "<td><form name='getjob' method='post' action='update.php'>
  <input type='hidden' name='job_id' id='job_id' value='" . $row['job_id'] . "'>
  <input type='submit' name='button' id='button' value='Pickup Job'>
  </form></td>";
  
  echo "</tr></table>";
```


----------



## randyrr (May 28, 2009)

Hi Redcore,

now the value is passing, but the table does not update....

Could u assist. The same php query above....

Hey RedCore, I figured it out.... i forgot the

```
$result = mysql_query($query);
```
 at the end...thanks anyways!!!!

randyrr
[[--merged from double-posting —dm01]]
new problem redcore

i want to insert into two separate tables although where the names are the same

here's my php code:


```
$sql = "INSERT INTO booking (name_title,first_name,last_name,phone,email,pickup_address_no,pickup_address_name,pickup_comments,date,time,am_pm,vehicle,destination_street,destination_accommodation,option_wheelchair,option_babycapsule,option_childseat,other_special_needs) VALUES ('$formname_title','$formfirst_name','$formlast_name','$formphone','$formemail','$formpickup_address_no','$formpickup_address_name','$formpickup_comments','$date','$time','$formam_pm','$formvehicle','$formdestination_street','$formdestination_accommodation','$formoption_wheelchair','$formoption_babycapsule','$formoption_childseat','$formother_special_needs')" or die ("cannot create booking");
   
   $result =mysql_query($sql);



		$formdestination_street = $_POST['destination_street'];
		echo "</br>";

		$formpickup_address_name = $_POST['pickup_address_name'];
		echo "</br>";


	$sql ="Insert into jobs (destination_address, pickup_address_name, job_status) VALUES ('$formdestination_street','$formpickup_address_name',1)" or die (mysql_error());
	
	$result =mysql_query($sql);
```
it doesn't work...only the 1st select statement works so i don't know what to do...
[[--merged from double-posting, guess that'd make this a triple post —dm01--]]
fixed issue

_[[Moderator's Note: please try not to make consecutive postings. You can either ask a staff member (via PM) to edit your original post, or to merge consecutive postings. When we have to do it for you we get kind of annoyed. Thank you for helping us keep TSF a nice place for everyone to visit.--]]​_


----------



## randyrr (May 28, 2009)

*** fixed previous issue ***

new question

What i'm trying to get at is this:

there are 3 types of vehicles 
v1 = 5 seats
v2 = 4 seats
v3 = 3 seats


If the vehicle selected = v1

then 
1. check is seating is available
2. create booking
3. decrease the number of available seats

until availability = 5

4. display error


how to write it in a loop (if, while..do or for ).


----------



## Redcore (Aug 14, 2007)

You'd use an array and do a "for" loop to check the amount of available seats, create the booking, and alter the array (to remove a seat).


----------



## randyrr (May 28, 2009)

Hey,

This is my js form

function FrontPage_Form1_Validator(theForm)
{
if (theForm.student_fname.value == "")
{
alert("Please enter your \"First Name\" .");
theForm.student_fname.focus();
return (false);
}

if (theForm.student_fname.value.length < 3)
{
alert("Please enter at least 3 characters in the \"First Name\" field.");
theForm.student_fname.focus();
return (false);
}

if (theForm.student_fname.value.length > 20)
{
alert("Please enter at most 20 characters in the \"First Name\" field.");
theForm.student_fname.focus();
return (false);
}

if (theForm.student_lname.value == "")
{
alert("Please enter your \"Last Name\" .");
theForm.student_lname.focus();
return (false);
}

if (theForm.student_lname.value.length < 3)
{
alert("Please enter at least 3 characters in the \"Last Name\" field.");
theForm.student_lname.focus();
return (false);
}

if (theForm.student_lname.value.length > 20)
{
alert("Please enter at most 20 characters in the \"Last Name\" field.");
theForm.student_lname.focus();
return (false);
}

if (theForm.student_address_no.value == "")
{
alert("Please enter your contact \"Address\".");
theForm.student_address_no.focus();
return (false);
}

if (theForm.student_phone.value == "")
{
alert("Please enter your contact \"Phone\" number.");
theForm.student_phone.focus();
return (false);
}

if (theForm.student_street_name.value == "")
{
alert("Please enter your contact \"Phone\" number.");
theForm.student_street_name.focus();
return (false);
}

if (theForm.student_phone.value == "")
{
alert("Please enter your contact \"Phone\" number.");
theForm.student_phone.focus();
return (false);
}


if (theForm.student_phone.value.length < 7)
{
alert("Please enter at least 7 characters in the \"Phone\" field.");
theForm.student_phone.focus();
return (false);
}

if (theForm.student_phone.value.length > 10)
{
alert("Please enter at most 10 characters in the \"Phone\" field.");
theForm.student_phone.focus();
return (false);
}

if (theForm.student_email.value == "")
{
alert("Please enter your contact \"Email\" address.");
theForm.student_email.focus();
return (false);
}

if (theForm.student_username.value == "")
{
alert("Please enter your contact \"Email\" address.");
theForm.student_username.focus();
return (false);
}

if (theForm.student_password.value == "")
{
alert("Please enter your contact \"Email\" address.");
theForm.student_password.focus();
return (false);
}


if (theForm.student_password.value !== theForm.student_password2.value)
{
alert("Your password does not match");
theForm.student_password.focus();
return (false);
}

return (true);
}



how can i check validation against apostrophes (')being entered in the database, 
as well as proper email validation, using the above script?

thanks randyrr


----------



## Redcore (Aug 14, 2007)

No idea, I'm not a JS guy


----------



## ahmorrow (May 5, 2009)

Here ya go.

```
function FrontPage_Form1_Validator(theForm)
{

///////////////////////////////CHANGES BEGIN HERE///////////////////////////////

/* This passes the variables in the form to the function checkForApost and
   removes the apostrophes in all variables listed below                      */
checkForApost(theForm.student_fname.value);
checkForApost(theForm.student_lname.value);
checkForApost(theForm.student_address_no.value);
checkForApost(theForm.student_student_phone.value);
checkForApost(theForm.student_street_name.value);
checkForApost(theForm.student_username.value);
checkForApost(theForm.student_password.value);
checkForApost(theForm.student_email.value);

// This is the function mentioned above.
function checkForApost(temp)
if(temp.match("'"))
{
var apost=tmp.replace("'","");
theForm.student_username.value=ne;
}

function echeck(str) {


/* DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
Frm:  [email protected]
I know this next part isn't exactly written by me, but it works.  This "SHOULDN'T" need any changes.
*/

var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
   alert("Invalid E-mail ID")
   return false
}

if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
   alert("Invalid E-mail ID")
   return false
}

if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
    alert("Invalid E-mail ID")
    return false
}

 if (str.indexOf(at,(lat+1))!=-1){
    alert("Invalid E-mail ID")
    return false
 }

 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
    alert("Invalid E-mail ID")
    return false
 }

 if (str.indexOf(dot,(lat+2))==-1){
    alert("Invalid E-mail ID")
    return false
 }
	
 if (str.indexOf(" ")!=-1){
    alert("Invalid E-mail ID")
    return false
 }

 return true					
}

function ValidateForm(){
var emailID=theForm.student_email.value;
	
if ((emailID.value==null)||(emailID.value=="")){
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (echeck(emailID.value)==false){
emailID.value=""
emailID.focus()
return false
}
return true
}

/////////////////////////////////END OF CHANGES/////////////////////////////////

if (theForm.student_fname.value == "")
{
alert("Please enter your \"First Name\" .");
theForm.student_fname.focus();
return (false);
}

if (theForm.student_fname.value.length < 3)
{
alert("Please enter at least 3 characters in the \"First Name\" field.");
theForm.student_fname.focus();
return (false);
}

if (theForm.student_fname.value.length > 20)
{
alert("Please enter at most 20 characters in the \"First Name\" field.");
theForm.student_fname.focus();
return (false);
}

if (theForm.student_lname.value == "")
{
alert("Please enter your \"Last Name\" .");
theForm.student_lname.focus();
return (false);
}

if (theForm.student_lname.value.length < 3)
{
alert("Please enter at least 3 characters in the \"Last Name\" field.");
theForm.student_lname.focus();
return (false);
}

if (theForm.student_lname.value.length > 20)
{
alert("Please enter at most 20 characters in the \"Last Name\" field.");
theForm.student_lname.focus();
return (false);
}

if (theForm.student_address_no.value == "")
{
alert("Please enter your contact \"Address\".");
theForm.student_address_no.focus();
return (false);
}

if (theForm.student_phone.value == "")
{
alert("Please enter your contact \"Phone\" number.");
theForm.student_phone.focus();
return (false);
}

if (theForm.student_street_name.value == "")
{
alert("Please enter your contact \"Phone\" number.");
theForm.student_street_name.focus();
return (false);
}

if (theForm.student_phone.value == "")
{
alert("Please enter your contact \"Phone\" number.");
theForm.student_phone.focus();
return (false);
}


if (theForm.student_phone.value.length < 7)
{
alert("Please enter at least 7 characters in the \"Phone\" field.");
theForm.student_phone.focus();
return (false);
}

if (theForm.student_phone.value.length > 10)
{
alert("Please enter at most 10 characters in the \"Phone\" field.");
theForm.student_phone.focus();
return (false);
}

if (theForm.student_email.value == "")
{
alert("Please enter your contact \"Email\" address.");
theForm.student_email.focus();
return (false);
}

if (theForm.student_username.value == "")
{
alert("Please enter your contact \"Email\" address.");
theForm.student_username.focus();
return (false);
}

if (theForm.student_password.value == "")
{
alert("Please enter your contact \"Email\" address.");
theForm.student_password.focus();
return (false);
}

if (theForm.student_password.value !== theForm.student_password2.value)
{
alert("Your password does not match");
theForm.student_password.focus();
return (false);
}

return (true);
}
```


----------



## randyrr (May 28, 2009)

ohhhkk, i'm so sorry..

here's my register.html form with i used to the js code u supplied so i didn't post it again...


```
<form method="post" action="php/checkuser.php" onsubmit="return FrontPage_Form1_Validator(this)">   

			 <h2 style="color:#FFFFFF">Register</h2>
			  
			  <div class="reg" style="margin-top:20px; margin-bottom: 0">
			  <ol>
				<li>
				  <label for="student_fname"> First Name<em>*         </em></label>
				  <input name="student_fname" id=""/>
				</li>
				<li>
				  <label for="student_lname"> Last Name<em>*          </em></label>
				  <input name="student_lname" id=""/>
				</li>
				<li>
				  <label for="student_address_no">Address No<em>*        </em></label>
				  <input name="student_address_no" id=""/>
				</li>
				<li>
				  <label for="student_street_name">Street Name       </label>
				  <input name="student_street_name" id=""/>
				</li>
				<li>
				  <label for="student_phone">Phone<em>*               </em></label>
				  <input name="student_phone" id=""/>
				</li>
				  <li>
				  <label for="student_email">Email<em>*                 </em></label>
				  <input name="student_email" id=""/>
				  </li>
				  <li>
				  <label for="student_username">Username<em>*          </em></label>
				  <input name="student_username" id=""/>
				  </li>
				  <li>
				  <label for="student_password">Password<em>*           </em></label>
				  <input name="student_password" type="password" id=""/>
				  </li>
				  <li>
				  <label for="student_password2">Confirm Password<em>*</em></label>
				  <input name="student_password2" type="password" id=""/>
				  </li>	
			 </ol>
					<input type="submit" value="Register" style="margin-top:30px; margin-bottom:0px;margin-left:150px;"/>
					<input type="reset" value="Reset" style="margin-top:30px; margin-bottom:0px;margin-left:0px;"/>
					</form>
```

and this is my checkuser.php code, which appears to be ok


```
<?php


// Connect to the server			
		$db = mysql_connect("localhost", "root", "test") 
		or die("testing connection");
		echo ("connected");		

// connect to the db
		mysql_select_db("educational", $db) or
		die("cannot connect to the database");
		echo(" <br />Connection  successful<br/>");

	$formstudent_fname = $_POST['student_fname'];
	echo "</br>"; 
	$formstudent_lname = $_POST['student_lname'];
	echo "</br>"; 
	$formstudent_address_no = $_POST['student_address_no'];
	echo "</br>"; 
	$formstudent_street_name = $_POST['student_street_name'];
	echo "</br>"; 
	$formstudent_phone = $_POST['student_phone'];
	echo "</br>"; 
	$formstudent_email = $_POST['student_email'];
	echo "</br>"; 
	$formstudent_username = $_POST['student_username'];
	echo "</br>"; 
	$formstudent_password = md5($_POST['student_password']);
	echo "</br>"; 
	$formstudent_password2 = md5($_POST['student_password2']);
	echo "</br>";
	$random_key = uniqid(); //uniqid() generates a random string

//check to see if the name exists in the current event table
//$query = "SELECT student_username FROM student WHERE student_username = '$formstudent_username' // ";
$query = "SELECT student_username FROM student WHERE student_username = '" 
    . mysql_escape_string($formstudent_username). "'";

$results = mysql_query($query);
	if (!$results) die('query failed');


// this makes sure both passwords entered match
//if ($_POST['student_password'] != $_POST['student_password2']); {
//die('Your passwords did not match. ');
//}

// here we encrypt the password and add slashes if needed
$_POST['password'] = (md5($_POST['password']));
if (!get_magic_quotes_gpc()) {
$_POST['password'] = addslashes($_POST['password']);
$_POST['username'] = addslashes($_POST['username']);
}	


if (!mysql_num_rows($results) == 0) {	 //exists within the table
echo "We're sorry, but this username is already taken, please try another username <a href=../register.html> Click this link to register again</a>";
//*** output the list of names within the database
mysql_close();

//possible return FALSE?

} else { //does not exist within this table, continue & add to table
$results = "INSERT INTO student (student_fname,student_lname,student_address_no,student_street_name,student_phone,student_email,student_username,student_password,student_password2,active,activekey) VALUES ('$formstudent_fname','$formstudent_lname','$formstudent_address_no','$formstudent_street_name','$formstudent_phone','$formstudent_email','$formstudent_username','$formstudent_password','$formstudent_password2',0,'$random_key')";


echo "<p>Thank you, $formstudent_fname, for registering with us, you may <a href=../login.html>login</a> now.<br /></p>";


if (!mysql_query($results)) {
echo "<p>We were unable to insert this record.<br />The error was: </p>" .

mysql_error();
mysql_close();
}
}
?>
```

So unfortunately, it did not check for apostrophes or correct email format 


thanks again.....randyrr


----------



## ahmorrow (May 5, 2009)

Thanks Randy, I'll take a look at it and see what I can do. May be a few hours, definitely by tomorrow.
[[--merged from double-post —dm01 --]]
Alright, try replacing the html file you're currently using with this. EVERYTHING. Don't try to change anything just yet. We'll work on posting it to the php file soon, but now we need to test and be sure the validation is working correctly.


```
<html>
<head>
<script type="text/javascript">
function validateFormOnSubmit(theForm) {
var reason = "";

  reason += validateUsername(theForm.student_username);
  reason += validatePassword(theForm.student_password,theForm.student_password2);
  reason += validateEmail(theForm.student_email);
  reason += validatePhone(theForm.student_phone);
  reason += validateStNo(theForm.student_address_no);
  reason += validateStName(theForm.student_street_name);
      
  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }

  alert("All fields are filled correctly");
  return false;
}
function validateStNo(fld) {
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = "You didn't enter a street number.\n";
    } else if (isNaN(fld.value)=true && fld.value<=1) {
        fld.style.background = 'Yellow';
        error = "Your street number is not a valid number."
    } else {
        fld.style.background = 'White';
    }
    return error;  
}
function validateStName(fld) {
    var error = "";

    if (fld.value.length == 0) {
        fld.style.background = 'Yellow';
        error = "You didn't enter a street name.\n";
    } else if (isNaN(fld.value)=false) {
        fld.style.background = 'Yellow';
        error = "Your street name should not contain numbers.";
    } else {
        fld.style.background = 'White';
    }
    return error;
}
function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
 
    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "You didn't enter a username.\n";
    } else if ((fld.value.length < 5) || (fld.value.length > 20)) {
        fld.style.background = 'Yellow'; 
        error = "The username needs to be between 5-20 characters.\n";
    } else if (illegalChars.test(fld.value)) {
        fld.style.background = 'Yellow'; 
        error = "The username contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}
function validatePassword(fld,fld2) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers 
 
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter a password.\n";
    } else if ((fld.value.length < 6) || (fld.value.length > 20)) {
        error = "The password must be between 6-20 characters.\n";
        fld.style.background = 'Yellow';
    } else if (illegalChars.test(fld.value)) {
        error = "The password must only contain letters and numbers.\n";
        fld.style.background = 'Yellow';
    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The password must contain at least one numeral.\n";
        fld.style.background = 'Yellow';
    } else if (fld.value !== fld2.value) {
        error = "Passwords do not match.\n";
        fld.style.background = 'Yellow';
        fld2.style.background = 'Yellow';
    } else {
        fld.style.background = 'White';
    }
   return error;
}  
function trim(s)
{
  return s.replace(/^\s+|\s+$ '');
}
function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@][email protected][^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}
function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld.value == "") {
        error = "You didn't enter a phone number.\n";
        fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "The phone number contains illegal characters.\n";
        fld.style.background = 'Yellow';
    } else if (!(stripped.length == 10)) {
        error = "The phone number is the wrong length. Make sure you included an area code.\n";
        fld.style.background = 'Yellow';
    }
    return error;
}
</script>
</head>
<body> 
<form name="myForm" onsubmit="return validateFormOnSubmit(this)" action="">
<table>
  <tbody>
  <tr>
    <td><label for="student_username">Your user name:</label></td>
    <td><input name="student_username" size="20" maxlength="20" type="text"></td>
  </tr>   
  <tr>
    <td><label for="student_password">Your password:</label></td>
    <td><input name="student_password" size="20" maxlength="20" type="password"></td>
  </tr>
  <tr>
    <td><label for="student_password2">Confirm Password:</label></td>
    <td><input name="student_password2" size="20" maxlength="20" type="password"></td>
  </tr>   
  <tr>
    <td><label for="student_email">Your email:</label></td>
    <td><input name="student_email" size="20" maxlength="20" type="text"></td>
  </tr>  
  <tr>
    <td><label for="student_phone">Your 10-digit telephone number:</label></td>
    <td><input name="student_phone" size="20" maxlength="10" type="text"></td>
  </tr>   
  <tr>
    <td><label for="student_address_no">Street Number:</label></td>
    <td><input name="student_address_no" size="20" maxlength="5" type="text"></td>
  </tr>    
  <tr>
    <td><label for="student_street_name">Street Name:</label></td>
    <td><input name="student_street_name" size="20" maxlength="20" type="text"></td>
  </tr>   
  <tr>
    <td> </td>
    <td><input name="Submit" value="Send" type="submit" ></td>
    <td> </td>
  </tr>
  </tbody>
</table>
</form> 
</body>
</html>
```
_[[Moderator's Note: Please do not double post. Ask a member of staff to either edit your original post or to merge consecutive posts. We don't get annoyed if you ask. —dm01]]​_


----------



## randyrr (May 28, 2009)

hey ahmorrow,

I've just tried it AS IS, but no change.... it doesn't detect nulls either, i've used FF and IE  

thanks still though....randyrr


----------



## ahmorrow (May 5, 2009)

It's working fine in FF3.5


----------



## randyrr (May 28, 2009)

kk....

ahmorrow, i'm still checking the js, i will provide some feedback tonight...however, 
Redcore,

I want to update my database by loading the values that the user entered when 

registering, how can i get that to work.

randyrr


----------



## ahmorrow (May 5, 2009)

I have no experience in PHP, but the logical thing to do would be to check if they're logged in and if they're not redirect them to that page. One page you might want to keep the redirect off of--and what might be causing the redirect error is the login page.

If you go to the login page and it checks to see if you're logged in and redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then redirects you the login page and then checks to see if you're logged in and then...

You get the idea


----------



## Redcore (Aug 14, 2007)

^ LOL

I believe a $_SESSION variable is all you need when they login.


----------



## randyrr (May 28, 2009)

a session variable to return registration form, with database values??

How do i use the session username (whether it was reg'd or not) to find the correct row in the database e.g. SEL * from users where (session_id) = $_session....o something like that


----------



## randyrr (May 28, 2009)

If i Uploaded an image to a particular directory, how do i display it then, a variable, therefore if another user uploads a photo, then only his/her photo will be shown as a profile pic?


----------



## ahmorrow (May 5, 2009)

It looks a little like this....

```
[php]php here![/php]
```


----------



## randyrr (May 28, 2009)

Hey ahmorrow,

i've just checked the js and it's not working....


```
?student_username=ewqfrewfewf'&student_password=dqdf'&student_password2='''''&student_email=%3Bqfdef'&student_phone=deqdd'&student_address_no=wfefw&student_street_name=fewfewf'&Submit=Send#
```
as u can see everything (invalid entries) goes into the browser url...


----------



## ahmorrow (May 5, 2009)

Sorry about that, try this one.


ahmorrow said:


> ```
> <html>
> <head>
> <script type="text/javascript">
> ...


----------



## Redcore (Aug 14, 2007)

randyrr said:


> How do i use the session username (whether it was reg'd or not) to find the correct row in the database e.g. SEL * from users where (session_id) = $_session....o something like that


Is this for PHP or JS? I meant for PHP.

You'd register a session variable like this (real simple):

```
$_SESSION['session_id'] = $session;
```
Then you'd call it like this:

```
mysql_query("SEL * from users where (session_id) = ".$_SESSION['session_id']."");
```


----------



## randyrr (May 28, 2009)

ahmorrow said:


> Sorry about that, try this one.
> 
> 
> ahmorrow said:
> ...


----------



## randyrr (May 28, 2009)

any luck with the js?....helppppppppp!!!


----------

