?
Solved

PHP survey form

Posted on 2006-05-25
36
Medium Priority
?
756 Views
Last Modified: 2010-05-18
Hi!

I am creating an online PHP survey form.

I have two problems:
Problem 1:
I want to display "Your response is valid. Please try again" message only when any of the survey respondent's input failed validation. Currently, even though a suubject' response failed validation, it continues and display an invalid response on the screen.

Problem 2:

When a respondent's input passed validation, I would like to display the input in a table with the field name being placed at the first column (usually, field name is located in the first row of a table) and respondent's input being placed in the second column.

Hope and believe that you experts may kindly help me again!

In a few minutes, I am going to upoad my work in my web page (www.nice-man.com), and click "Download survey scripts".

Thanks a lot!

duta
May 25, 2006, at 1 pm

___________________________ form.php _____________________________________


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body bgcolor="cccccc">


<form action="process.php" method="POST">
<ul>
<h2 align="center">Online Survey</h2></FONT></ul><br><br>

<ul><ul>


<p><li><strong>Name:</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input TYPE="TEXT" NAME="name" size="35" /><br>

</li>



<p><li><strong>Email Address:</strong>&nbsp;&nbsp;
<input TYPE="TEXT" NAME="email" size="35" /><br>

</li>

<p><li><strong>Year in School:</strong><br><br>
<input TYPE="RADIO" NAME="year" value="freshman" size="35" />            Freshman  ;
<input TYPE="RADIO" NAME="year" value="sophomore" size="35" />                      Sophomore ;
<input TYPE="RADIO" NAME="year" value="junior" size="35" />                  Junior ;
<input TYPE="RADIO" NAME="year" value="senior" size="35" />                  Senior ;

</ul></ul>
<ul><ul>
<br><br>
<input TYPE      ="SUBMIT"   NAME="SUBMIT"            VALUE="Submit"  />
<input TYPE      ="RESET"         NAME="RESET"            VALUE="Reset"    />

</li>
</ul></ul>
</form>
</body>
</html>
__________________________________ dbconnect.php _______________________________


<?php
//Set up variables

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';    

?>

<?php
//Include Connection File
require_once("db.php");
?>

<?php
//Connect to MYSQL
$dbh = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to MySQL");

//Select database
$selected = mysql_select_db("lab",$dbh) or die("Could not select database table");

//Establish a database connection
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
?>



________________________________ process.php _____________________________________________


<?php


require_once("dbconnect.php");
?>

<?php

      



$pass                  = true;
$name            = "";
$email            = "";
$year                  = "";



function check_name ($name)
      {
           $watch= '^[[:alpha:]\.\' \-]{2,15}$';
     
            if (eregi ($watch, stripslashes(trim($name))))
      
            return true;
          else return false;
      }


function check_email($email)
      {
             $watch = '^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]{2,})+$';
             if (eregi($watch, $email))
        return true;
             else return false;
      }

 
 // name
if(empty($_POST["name"]))
      {
            $pass = false;
            echo "You didn't enter your name accurately.<br><br>";
            
      }
elseif (!check_name($_POST["name"]))
      {
            echo "Invalid name.";
      }
else
      {
            
            $name = trim($_POST["name"]);
      }




// email
if(empty($_POST["email"]))
      {
            $pass = false;
            echo "You didn't enter your email address accurately.<br><br>";
            
      }
elseif (!check_email($_POST["email"]))
      {
            echo "Invalid email address.";
            $pass = false;
      }
else
      {
            //use trim() just to remove any leading or trailing empty spaces
            $email = trim($_POST["email"]);
            $pass = true;
      }


// Year
if(empty($_POST["year"]))
      {
            $pass = false;
            echo "Select your year in school.<br><br>";
      }
else
      {
            //use trim() just to remove any leading or trailing empty spaces
            $year = trim($_POST["year"]);
      }

?>

<?php
//Now, if validation fails, display "You put an invalid response. Please try again" message, and quit.
// Currently, even if some of  client's response were invalid, it continues.
if($pass = false )
{
      echo "You put an invalid response. Please try again!";
}

// If any of above validation fails,
else
{
?>

<br><br>
<h3> <?php echo $name; ?>, thank you for your response. Here are your records <br> which has been recorded in our database: </h3>

<?php
//Display inputs


            echo "<strong>Name:      </strong>                              ".$name.                              "<br />";
            echo "<strong>Email Address:      </strong>                  ".$email.                              "<br/ >";
            echo "<strong>Year in School:      </strong>            ".$year.                              "<br />";
            

<?php
}//End main IF
?>

<?php
//Close connection
mysql_close();
?>
_________________________________________________________________________________________










0
Comment
Question by:duta
  • 22
  • 14
36 Comments
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16763140
What you asked could take very little code, or a bunch.  Here is an example:

>Problem 1:
> I want to display "Your response is valid. Please try again" message only when any of the survey respondent's input
> failed validation. Currently, even though a suubject' response failed validation, it continues and display an invalid
> response on the screen.

The easy part is:
YOUR CODE:
if($pass = false )
CORRECT CODE:
if($pass == false )

You correctly used a boolean ($pass) and you used it correctly all the way down to that comparison.

Problem 2:
> When a respondent's input passed validation, I would like to display the input in a table with the field name being
> placed at the first column (usually, field name is located in the first row of a table) and respondent's input being
> placed in the second column.

Just format your code at the end into a table:
          echo "<strong>Name:     </strong>                         ".$name.                         "<br />";
          echo "<strong>Email Address:     </strong>               ".$email.                         "<br/ >";
          echo "<strong>Year in School:     </strong>          ".$year.                         "<br />";
 
Something like:
          echo "<table>";
          echo "<tr><th>Name:</th><td>$name</td></tr>";
          echo "<tr><th>Email Address:</th><td>$email</td></tr>";
          echo "<tr><th>Year in School:</th><td>$year</td></tr>";
          echo "</table>";

Notice the double string optimazation.  A varaible $name has its value printed in a double quoted string.
$name = 'Joe';
print "$name"; // prints Joe
print '$name'; // prints $name

And the table formatting is pretty straightforward.  Normally you see just <tr> (table row) and <td> (table data).  <th> is table hearder and bolds (strong's) the text inside it.

Enjoy
Joe P

(Also you can stop many of your errors by putting some javascript validation on the html page, ask if you would like some!)
0
 

Author Comment

by:duta
ID: 16763209
TO: BogoJoker:

Thank you so much for your very kind, prompt response.
I am a very beginner, and my scripts look very awkward. I should improve it a lot.

By the way, I will modify my scripts as you kindly advised and test them. I will come back to you soon.

Thanks a lot!

duta
May 25, 2006, at 1:47 p.m.

I
0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16763617
Sure, if you request it and you stick around until tommorrow (my last final exam is tonight) then I could probably go through and suggest improvements.  I normally try to do something like that, I was in the same position as you were a few months ago, the experts here have helped me out a ton!

For now lets focus on the main questions, it is likely other experts will post some advice so you will get a couple points of views.  

Until tommorrow,
Joe P
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:duta
ID: 16763840
TO: Bogojoker:

Thank you again for your very kind, prompt response. I feel very moved to know that you are trying to help me out even when you have an exam hours away. Certainly, I can wait till tomorrow or the day after tomorrow.
The table format you suggested worked just fine. By all means, it seems that you are much brighter than me.

Good luck with your test.

Thanks again!

duta
May 25, 2006, at 2:55 p.m.
0
 

Author Comment

by:duta
ID: 16764594
TO: BogoJoker:

You said: "Also you can stop many of your errors by putting some javascript validation on the html page, ask if you would like some!"

Me: "Yes, I would certainly very much like to try them.
       Thanks!"

duta
May 25, 2006, at 4:12 p.m.

0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16766303
Okay I had some fun and I played around with the page and made this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Online Survey</title>
<style type="text/css">
tr th
{
  text-align: center;
  width: 150px;
  height: 30px;
}
h1
{
  margin: 0 auto;
  margin-bottom: 20px;
  text-align: center;
  width: 400px;
  border-bottom: 1px dashed;
}
table
{
  margin: 0 auto;
}
.sig { position: absolute; bottom: 0; right: 10px; text-align: right; color: white; }
</style>
<script type="text/javascript">
function validate(form)
{
  // Test Name
  var regex = /^[a-zA-Z ]+$/;
  if (!regex.test(form.name.value))
  {
    alert("Name must be non-empty and contain letters and spaces only!");
    form.name.focus();
    return false;
  }
 
  // Test Email
  regex = /^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+.)+(com|net)$/;
  if (!regex.test(form.email.value))
  {
    alert("Email is not valid!");
    form.email.focus();
    return false;
  }
 
  // Test Radio Buttons
  var somethingChecked = false;
  for (var i = 0; i < form.year.length; i++)
  {
    if (form.year[i].checked)
      somethingChecked = true;
  }
 
  if (!somethingChecked)
  {
    alert("Make sure to check your year!");
    return false;
  }

  // Passed All Tests
  return true;
}
</script>

</head>

<body bgcolor="#cccccc">
<br><h1>Online Survey</h1><br>

<form action="process.php" method="POST">
<table>
  <tr>
    <th>Name:</th>
    <td><input type="text" name="name" size="28"></td>
  </tr>
  <tr>
    <th>Email:</th>
    <td><input type="text" name="email" size="28"></td>
  </tr>
  <tr>
    <th>Year in School:</th>
    <td>
      <table>
        <tr><td><input type="radio" name="year" value="freshmen"> Freshman</td>
        <td><input type="radio" name="year" value="sophomore"> Sophomore</td></tr>
        <tr><td><input type="radio" name="year" value="junior"> Junior</td>
        <td><input type="radio" name="year" value="senior"> Senior</td></tr>
      </table>
    </td>
  </tr>
  <tr><td><br></td></tr>
  <tr>
    <td colspan="2" align="center">
      <input type="submit" value="Submit" onClick="return validate(this.form);">&nbsp;
      <input type="reset" value="Reset">
    </td>
  </tr>
</table>
</form>

<div class="sig">Custom Designed Form</div>
</body>
</html>

The little change is that there are a bunch of tables.  I just played with them to make some nice formatting for the form.  I put it into a text editor to make indent the code to make it easier for you to read.  When you take a first look at the code don't look at the <style> or the <script> look at the tables and see if you understand them.  Basically there is one major table, each part (Name, Email, Year) is a <tr> table row, each with a <th> table header (which bolds automatically), and a <td> table data.  The last gets a little complicated, inside the <td> is another table itself!  Why? Just to format it cleanly.  Basically its a table with 2 rows, each with 2 columns (2<tr> and 2<td>) that hold the radio buttons.

Now I will tell you about the <script> because that is what this is all about.  Its just some simple javascript.  You will notice that is a function.  You probably know what a function is (also known as a subroutine or a method), basically when an event happens (something is clicked or something happens) then we can call a function.  That is exactly what I did, when someone clicks the Submit button (<input type="submit" ... onClick="return validate(this.form);">) it calls validate method(), sending it the form as a parameter.  Now, this is not  100% cross browser compatable, I would be happy to make the very slight changes necessary to make it work but for now this is the easiest way to show you the javascript then I will show you how to make it capable for all browsers!  The validate() method is pretty straightforward except for those regex statements.  If you do not know regular expressions it is okay.  Basically the first regex tests if it is 1 or more letters and spaces.  If not it prints that alert and returns false.  The second checks for a legit email address (from the Firefox add-on predefined regex modified slightly by me).  Again, if it fails there is an alert message, focusing in on the email textbox then a return false.  The last check is the most complex and I will explain it later, right now this is getting wordy!

Finally my favorite part, the <style>.  You have probably heard of CSS.  I personally think that it should be taught along with html from the beginning because it is so nice.  The <style> I provided is some of the most basic.  The h3 { ... } means all <h3> tags in your body will get that style applied to it.  Also the tr th { ... } means all the <th> inside a <tr> (yes that is the correct order) get that style applied.  The styles are straightforward, you can read and understand what it means.  There are a few I will explain:
margin: 0 auto;  <-- this centers the text.
It is a very shorthand version of all four,
margin-top: 0; margin-bottom: 0; margin-right: auto; margin-left: auto;
in just one line!  That basically does what <center> does, only you don't need to write <center> now!!
Lastly the .sig { ... }, notice in the bottom right of the screen it has some white text, that is what .sig created.  In teh source of the html at the bottom there is <div class="sig"> well, .sig (the dot means anything with that class name) formats that.  The code in there is sorta complex if this is your first time but I will explain anything you want about this page, just feel free to ask, poke, and prod.

Right now the page I just posted should work with your PHP script.  Also it 100% valid HTML, validated by w3 standards.  If you make any changes make sure you let me know if it validates.  Your original code had 16 errors, many are extremely small like forgetting to close elements but for safe practice make sure your code validates and if you need to know how I can recommend some easy methods for firefox (extensions).  (If I have time tommorrow night I can look at your php script, maybe I can make some improvements).

Enjoy,
Joe P
0
 

Author Comment

by:duta
ID: 16768987
TO: BogoJoker:

Thank you so much for your very kind help.

I just checked your post. I will take a little time to test it, and will come back to you. Hope you did real well with your exam last night.  

You are great.  

Thanks a lot!

duta
May 26, 2006, at 8:42 am
0
 

Author Comment

by:duta
ID: 16769079
TO: BogoJoker:

Wow, your scripts worked just wonderful. I am very much looking forward to seeing your modification of my "process.php" script.
You did already everything to get the points that I offered. Without your any additional help that I will truly appreciate, I will give you the points. I know anything else you do for me beyond this point is a great bonus for me.

Thanks a lot!

duta

May 26, 2006, at 8:55 a.m.
0
 

Author Comment

by:duta
ID: 16769255
TO: BogoJoker:

You are a genius. Yes, I will poke, prod and do everything to learn as much as I can from your great script.

By the way, I have some more questions (probably too many).

The first question that comes to my head is:

"What do I need to type after "regex=" when I need to validate others like (1) phone numbers, (2) zip code and (3) street address?

The second question is:
And in the script below, do I need to replace "com\net" part with "com\net\org\edu\gov"?

The third question is: I see a script near the end of your script:

"<div class="sig">Custom Designed Form</div>
</body>
</html>

What is "<div class="sig">Custom Designed Form</div>" for? Is it to set up for some script or just a closing?

Finally, your explanation was so well-organized and easy to understand (you exactly know how to best help a beginner like me.


Thanks a lot!

duta

May 26, 2006, at


_____________________________Here is your script to validate email which worked just great __________________
// Test Email
  regex = /^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+.)+(com|net)$/;
_________________________________________________________________________________________________


0
 

Author Comment

by:duta
ID: 16769410
TO: BogoJoker:

I am sorry to ask you some more questions which you don't have to respond at all.

My first question is:
______________________________________________
 // Test Name
  var regex = /^[a-zA-Z ]+$/;
  if (!regex.test(form.name.value))
______________________________________________

In the above name validation script,  can you give just a little explanation about  /^[a-zA-Z ]+$/?
Does it mean: name should include only "a-z", "A-Z"? What does "$" mean? Why does "$" come with "+" to validate a name ( var regex = /^[a-zA-Z ]+$/;) and without "+" to validate an email address (regex = /^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+.)+(com|net)$/;)?



My second question is:
To validate a phone number, is this script right?:

________________________________________________
// Test Phone Number
  var regex = /^[0-9\-]+$/;
  if (!regex.test(form.phone_number.value))
_______________________________________________


I am afraid I am asking you too many questions to answer and get you tired, maybe exhausted after a big exam last night. Right now, you are the best teacher that I can find.

Thanks a lot!

May 26, 2006, at 9:38 am

0
 

Author Comment

by:duta
ID: 16769770
TO:BogoJoker:

Thank you so much for your very extraordinary help.

I think everything is working just great.

I just wonder whether there is a way to validate whether a client put 7-digit (or letter) social security number, and, for that matter, to validate whether a client put at least 7 numbers like 678-2345 or 6782345 (or 10 number like 345-456-3571 or 3454563571).

I am playing with your script and learning a lot. If you, by any chance, are too busy to respnd to my stupid questions, please do not bother. I will accept your great, great help in 2 days (I just thought that keeping this forum open is easier to communicate with you :) ).

Thanks again!

May 26, 2006, at 10:18 am

0
 

Author Comment

by:duta
ID: 16769825
TO: JogoPoker:

Because I am learning so much from doing something I need with great help from you and from others, I thought I would like to try more more with my current script.

I am very much interested in incorporating object-orineted programmming  (OOP) into my current script (which is actually your script though).

I just wonder whether you may demonstrate me and millions of others (who are learning from your work) how to incorporating OOP, if possible, into my current work.

Thanks again!

duta

May 26, 2006, at 10:23 am
0
 

Author Comment

by:duta
ID: 16772304
TO: BogoJoker:

Thank you again for your extraordinary help.

I am writing to let you know that on the some of the questions that I asked earlier, I found answers by self.

They are:

The first question that comes to my head is:

Q1: "What do I need to type after "regex=" when I need to validate others like (1) phone numbers, (2) zip code and (3) street address?

My Answer: Yes, I figured out.


Q2: The second question is:
And in the script below, do I need to replace "com\net" part with "com\net\org\edu\gov"?

My Answer: Yes, I added net|org|edu|gov.

Q3: The third question is: I see a script near the end of your script:

"<div class="sig">Custom Designed Form</div>
</body>
</html>

My Answer: Yes, it is to display copyright notice (which needs to be displayed always at the designated spot of the screen).

________________
For the rest of my early questions, I have not found an answer yet.

The remaining questions are:  (1) What is "$" (at the end of name validation script) for?, (2) Is there a simple way to validate whether a respondent  gave a compelte 7-letter(excluding "-") or 10-letter phone number, and for the same matter, a social security number?

In addition, I am very much looking forward to seeing "process.php" that you told me you might improve.

By poking and prodding your script, I have been learning a lot.

Thanks a lot!

duta
May 26, 2006, at 3:41 p.m.


0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16772934
Okay, I'm back for a tad before I submit my last homework in less then 2 hours!

This is turning into a fun project, I havn't looked at the php yet but I will clarify some things.  First is the regex, I see that you answered some of your questions but I woudl like to got through the regex that will hopefully allow you to even make your own regex expressions.  Here I go:

--------------------------------
Regular Expressions: regex
--------------------------------
Regular Expressions are great for validation, but they can be used for many many other things.  It is a method of "matching" certain text.  In validation you can check to see if something does NOT match the regular expression.  Here is the thing that took me forever to learn, regex are not in quotes, they are in /'s.  /this/ was a regular expression!

/a/ matches the letter a.
/[a-z]/ matches any letter between a or z
/a+/ matches a one or more times (Example: aa, aaa, aaaa, but NOT a blank!)
/a*/ matches a zero or more times!
But you need to look out, /a/ would match something like: bab, it would match the a in that word...
So to fix that you can put ^ and $, meaning it starts with ^, and ends with $
/a/ matchs: alphabet (matches it twice, both a's)
/^a/ matches: alphabet (just the first a)
/a$/ matches: alpha (just the last a)
/^a$/ ONLY MATCHS: a (nothing else, just a without a space before or after)

So with some of the basics out of the way, lets dig in:
We want a name.  Only allow letters and spaces.
/^[a-zA-Z ]+$/ (This matches any letter and space combination, notice it cannot be blank because the +, and notice there is a space inside the brackets to allow spaces.
But there is a tiny error: It matches both:
Joe P
(and)
 Joe P
(the second has a space, and in fact any number of spaces would work)

A couple work arounds, .trim() the incoming string to remove spaces in front or modify the regex slightly
/^\w[a-zA-Z ]+$/ (that is the same as) /^[a-zA-Z][a-zA-Z ]+$/ (because) \w is equal to [a-zA-Z] one time
Notice we can make it a little easier with a special character \w which is any alpha letter, (allow underscore I think)

So lets design one for a phone number.  A Couple things to learn:
/[0-9]/ matches a digit
/\d/ is the exact same thing, matchs a digit
/\d{3}/ matches 3 digits in a row (Examples: 123 111 809)

So, now the format of the phone number:
1) (###) ###-####
2) ###-###-####
You need to escape parenthesis because otherwise they have a special meaning which is very useful but not for us right now.

Regex for number one, paranthesis, 3 digits, space then the rest you can see:
/\(\d{3}\) \d{3}-d{4}/
Regex for number two:
/\d{3}-\d{3}-\d{4}/

Both together, allowing for either:
/((\(\d{3}\) )|(\d{3}-))\d{3}-\d{4}/
Belive it or not that matches:
555-555-5555 and (555) 555-5555
It has a lot of parenthesis with their special meaning instead of actually matching the actual aprenthesis.  So lets break it down, I will put a bunch of spaces in there to make it clear what is happening
(         (      \(\d{3}\)     )     |      (  \d{3}-    )        )
One set of parenthesis for everything.
One set of parenthesis for the (###) with a space after it
Then the | symbol which you have discovered means OR
One set of parenthesis for ###-
What happens is One of those two inner sections will happen ONLY ONE MUST HAPPEN AND BE PERFECT!
Then the rest of the regex is what was the same in both cases, ###-####.

I feel like I explained this poorly.  But I hope you got the basics.  I will be back pretty soon (in an hour or two) to explain some more stuff.

Quite quickly:
"<div class="sig">Custom Designed Form</div>
Because it has class="sig" that means that it gets the CSS style .sig { ... } applied to it.
The CSS did a few things:
1) text color white
... position: absolute allows for:
2) 0px from the bottom
3) 10px from the right

Sorry for this being rushed, I will be back later!
Joe P
0
 

Author Comment

by:duta
ID: 16773263
TO: BogoJoker:

You are truly awesome. It is incredible that you took time out of your extremely busy schedule (you had an exam last night and you had to submit a homework in less than two hours) to respond to my questions in such a wonderful way.

I am so happy to join this site and to come across great, great minds and hearts like you.

If you write a book or do something else, I think, you may help a lot of people.

Your explanation is just fabulous and is so easy to understand.
I bought and read several PHP and MySQL books that got the highest readers' feedback. But I am learning a lot more now doing this small project with geart help from you and a few others.

Please do not rush. You need to take some break after the exam and the homework. I can wait for days and even for weeks.

I will be very excited when I finish this small project.

Thanks a lot!

duta

May 26, 2006, at 6:42 p.m.

0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16773325
Sure thing, you don't need to thank me too much, I find this fun =)

Lets see what you wanted:
>Is there a simple way to validate whether a respondent  gave a complete 7-letter(excluding "-") or 10-letter phone number, and for the same matter, a social security number?

I went over phone numbers briefly, but just tell me the format you want it and I can build a regex for it.
Social Security Number isnt that tricky, the format is ###-##-####, so the regex is:
/^\d{3}-\d{2}-\d{4}$/
Remember that the ^ and $ in this case means that it must start with and end with the correct characters.
That is exactly the same as this regex:
/^[0-9]{3}-[0-9]{2}-[0-9]{4}$/
They are exactly the same, just \d is a shortcut for writing [0-9] just like \w is a shortcut for [a-zA-Z_]

> Now I will explain "sig" in some more detail
In the <style> CSS I have:
.sig { position: absolute; bottom: 0; right: 10px; text-align: right; color: white; }
That is the just one line for writing:
.sig
{
  position: absolute;
  bottom: 0;
  right: 10px;
  text-align: right;
  color: white;
}

The .sig means any html element with class="sig" will get this style applied to it.  This has some simple parts to it and some complex.  Lets start with position: abolute.  With position absolute you are allowed four new tags, left, right, top, bottom.  I wrote bottom: 0 and right: 10px.  That means 0 pixels from the bottom and 10 pixels from the right, so its whatever has class="sig" will be in the bottom right corner.

Last couple tings, color: white makes the text color white.  text-align: right aligns the text to the right (remember that it is 10px from the right corner).

So <div class="sig">Custom Design</div> puts the (WHITE) text Custom Design in the bottom right corner.  Its just a nice touch to make the page look cool. =)

I will look at the php some time soon, probably late tonight.
Joe P
0
 

Author Comment

by:duta
ID: 16774098
TO: BogoJoker:

You are so wonderful.  I can't thank you enough by all means.
The validation thing was hard to comprehend. Now I understand it pretty much all thanks to your kind explanation which was so easy to follow.

I can't and should not expect any more from you.

But I will be very muched excited to see your "process.php" script because I know you are so good.

Many thanks to you!

duta

May 26, 2006, at 11:29 p.m.
0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16774139
[dbconnect.php]
<?php
//Set up variables
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';

//Include Connection File
require_once("db.php");

//Connect to MYSQL
$dbh = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to MySQL: " . mysql_error());

//Select database
$selected = mysql_select_db("lab",$dbh) or die("Could not select database table: " . mysql_error());

//Establish a database connection
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql: ' . mysql_error());
?>

There was no need to open and close <?php tags, since it is all one php file!  So I just made it a tad smaller, maybe a little easier on the php parser?  Also I put mysql_error() into the error messages, those are standard so that any random person like me raeding the error message will recognize the exact error message and can provide better advise on fixing the problem.

Now for process.php I have a few questions.  Right now the logic is a little difficult to follow.  It says if the name is empty BUT an email is provided $pass is true!  I will make a script that does what I would do, so bare with me.

Joe P

0
 

Author Comment

by:duta
ID: 16774161
TO: BogoJoker:

Thank you so much for your very kind, prompt response.

Yes, now that I have validation scripts in "form.php", the validation scripts in "process.php" might be redundant, and may need to be removed.

Hope that you may understand my explanation.

Yes, I will bare with you which will be a lot of fun.

Thanks again!

duta

May 26, 2006, at 11:55 p.m.
0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16774170
No!  You should always have some simple validation server side.
Javascript can be turned off by the user, it can be turned off in the browser (Internet Explorer, Firefox...)  So the javascript might not check the validation.  So you should leave validation in the PHP.  I am actually looking at it right now and you allow certain characters in the name and domains in the email which I had not planned for.
1) The name allows characters: ' - .
2) The email allows any email address that ends in two or more letters:
joe@aa.aa would validate.
joe@aa.aaaaa would validate too.
I will use my own scripts for now, tell me your preference.

(almost done)
Joe P
0
 

Author Comment

by:duta
ID: 16774171
TO: BogoJoker:

Hi again!

I wonder whether I may ask you one quick question.

My question is: The validation script that you gave me worked great at my office (it catched almost all invalid input). But when I tried it at home tonight, invalid input was not detected at all. I just wondered why.

Thanks again!

duta
May 26, 2006, at 11:59 pm
0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16774176
Could be javascript in the browser?
Also make sure that you clear the cache and refresh the page so that you get the newest page.
0
 

Author Comment

by:duta
ID: 16774208
TO: BogoJoker:

Thanks a lot again for your kind, super-prompt response.

Wow, I didn't know that I needed to have a validation script in the server-side too.
On my preference, I think your preference might be the best choice for me too because I am not good enough to know which one might be better for me.

On the validation not working at my home computer, I cleared the cache (Internet Explorer >Tools> deleted cookies and deleted files (offline content). Did I do right? Or what else do I need to do to clear cache?

Thanks again!

duta
May 27, 2006, at 12:14 am
0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16774216
Do you have know if you have javascript disabled/enabled?
0
 

Author Comment

by:duta
ID: 16774247
TO: BogoJoker:

Thanks again for your kind, prompt response.

On javascript enabled/disabled, I think it was enabled.  To check it, I went to IE > Tools >Internet Opetions >Security >Customer Level >Scripting (I found all three options were enabled).
Anyway, because I need to keep the validation script in "process.php", I don't have to worry about it less.

I will continue to try to figure out why. I hope you may just concentrate on "process.php" , if you may.

Thanks again!

duta
May 27, 2006, at 12:31 a.m.


0
 
LVL 17

Accepted Solution

by:
BogoJoker earned 2000 total points
ID: 16774265
Here is my version of process.php:

<?php
// Connect to mysql
require_once("dbconnect.php");

//-------------------
// Process the Form
//-------------------

// If any of the POST elements are not set, redirect with error
$err = '';
if (!isset($_POST['name']))
  $err = 'form.php?err=Must+Provide+A+Name';
elseif (!isset($_POST['email']))
  $err = 'form.php?err=Must+Provide+An+Email';
elseif (!isset($_POST['year']))
  $err = 'form.php?err=Must+Provide+A+School+Year';

// if error: Redirect to form
if ($err != '')
{
  header("Location: $err");
  exit;
}

// Get the POST elements
$name = trim(htmlspecialchars($_POST['name']));
$email = trim(htmlspecialchars($_POST['email']));
$year = $_POST['year'];

// Check if name is valid
// VALID NAME: 2-15 characters, allow letters, space, single apostrophe, and hyphen
if (!preg_match('/^[a-zA-Z \.\'-]{2,15}$/', $name))
  $err = 'form.php?err=Invalid+Name';
// Check if email is valid
// VALID EMAIL: anything.example@something.com (com can be any 2 letters or com or net)
elseif (!preg_match('/^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+.)+([a-z]{2}|com|net)$/', $email))
  $err = 'form.php?err=Invalid+Email';

// if error: Redirect to form
if ($err != '')
{
  header("Location: $err");
  exit;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Success</title>
<style type="text/css">
tr th
{
  text-align: center;
  width: 150px;
  height: 30px;
}
h3, h2
{
  margin: 0 auto;
  width: 450px;
  text-align: center;
}
h3
{
  margin-bottom: 20px;
  border-bottom: 1px dashed;
}
table { margin: 0 auto; }
.sig { position: absolute; bottom: 0; right: 10px; text-align: right; color: white; }
</style>
</head>
<body bgcolor="#cccccc">
<br><br>
<h2><?php echo $name; ?></h2><br>
<h3>Thank you for your response.  Here is the data which has been recorded in our database:</h3>
<?php
// Display Inputs
echo "<table>";
echo "<tr><th>Name:</th><td>$name</td></tr>";
echo "<tr><th>Email Address:</th><td>$email</td></tr>";
echo "<tr><th>Year in School:</th><td>$year</td></tr>";
echo "</table>";

//Close connection
mysql_close();
?>
<div class="sig">Survey Completed!</div>
</body>
</html>

-------------------------------------------------------------------------------------
Note: There needs to be a special addition to form.html (now form.php)
-------------------------------------------------------------------------------------
<?php
$err = "";
if (isset($_GET['err']))
  $err = $_GET['err'];
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Online Survey</title>
<style type="text/css">
tr th
{
  text-align: center;
  width: 150px;
  height: 30px;
}
h1
{
  margin: 0 auto;
  margin-bottom: 20px;
  text-align: center;
  width: 400px;
  border-bottom: 1px dashed;
}
table
{
  margin: 0 auto;
}
.sig { position: absolute; bottom: 0; right: 10px; text-align: right; color: white; }
.err { color: red; margin: 0 auto; text-align: center; }
</style>
<script type="text/javascript">
function validate(form)
{
  // Test Name
  var regex = /^[a-zA-Z][a-zA-Z ]+$/;
  if (!regex.test(form.name.value))
  {
    alert("Name must be non-empty and contain letters and spaces only!");
    form.name.focus();
    return false;
  }
 
  // Test Email
  regex = /^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+.)+(com|net)$/;
  if (!regex.test(form.email.value))
  {
    alert("Email is not valid!");
    form.email.focus();
    return false;
  }
 
  // Test Radio Buttons
  var somethingChecked = false;
  for (var i = 0; i < form.year.length; i++)
  {
    if (form.year[i].checked)
      somethingChecked = true;
  }
 
  if (!somethingChecked)
  {
    alert("Make sure to check your year!");
    return false;
  }

  // Passed all tests
  return true;
}
</script>

</head>

<body bgcolor="#cccccc">
<br><h1>Online Survey</h1><br>

<form action="process.php" method="POST">
<table>
  <tr>
    <th>Name:</th>
    <td><input type="text" name="name" size="28"></td>
  </tr>
  <tr>
    <th>Email:</th>
    <td><input type="text" name="email" size="28"></td>
  </tr>
  <tr>
    <th>Year in School:</th>
    <td>
      <table>
        <tr><td><input type="radio" name="year" value="freshmen"> Freshman</td>
        <td><input type="radio" name="year" value="sophomore"> Sophomore</td></tr>
        <tr><td><input type="radio" name="year" value="junior"> Junior</td>
        <td><input type="radio" name="year" value="senior"> Senior</td></tr>
      </table>
    </td>
  </tr>
  <tr><td><br></td></tr>
  <tr>
    <td colspan="2" align="center">
      <input type="submit" value="Submit" onClick="return validate(this.form);">&nbsp;
      <input type="reset" value="Reset">
    </td>
  </tr>
</table>
</form>
<p class="err"><?php echo "<br>$err"; ?></p>
<div class="sig">Custom Designed Form</div>
</body>
</html>


Okay these two pages together look pretty safe to me.  The documentation in the php pretty much speaks for itself at every step.  I use one variable $err throughout most of it, if there is ever an error I set $err to something.  If $err is blank then we know there were no errors!  I took out the functions to check the name and email and just tested them against a regular expression using preg_match.

The biggest change is that I now have error messages that appear on form.php!  Using the query string, just load this page in your browser:
form.php?err=This+Is+The+Error+Message
If you have the new form.php page you will see that message in red right at the bottom.  All the form data was lost (you can save that information in a couple different ways if you really want to).  But for now that is pretty nice.  I added style to the second page now, it looksa lot like the first page.

Enjoy,
Joe P

(Now even if the user has javascript disabled you should get the red error messages.  With javascript enabled though it is likely that the javascript will catch all of the errors and they will never see the error messages unless they stumble on the harmless query string form.php?err=Text)
0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16774266
Is this website up on the net so I can check it out?
Joe P
0
 

Author Comment

by:duta
ID: 16774285
TO: BogoJoker:

Thank you so much for your extraordinary help.

I am uploading the script now. It will take a few more minutes.

The URL is www.nice-man.com.

Thanks a lot!

duta

May 27, 2006, at 12:56 am



0
 

Author Comment

by:duta
ID: 16774302
TO: BogoJoker:

Hi again!

I just uploaded the latest one.

Hope you may figure it out.

It is so nice of you to write the scripts for me. It is just incredible for you to do all the things for me.
Hope you know that I am so grateful to you.

duta

May 27, 2006, at 1:03 am

0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16774304
Sure, this is a lot of fun and it is some experience for me. =)
0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16774317
Ooo, Check this out:

Instead of:
postion: absolute;

Use:
position: fixed;

Much cooler! =)
Joe P
0
 

Author Comment

by:duta
ID: 16774322
TO: BogoJoker:

Thanks again!

I will do that.

You are just fabulous!

duta

May 27, 2006, at 1:11 am

p.s.: You may be the most energetic person in experts-exchange which may well be proven by how quick and sincerely you responded to my calls for help :).
0
 

Author Comment

by:duta
ID: 16778551
TO:BogoJoker:

Thank you so much for your very extraordinary help.  With help, I am completing my survey work.

By the way, I wonder whether I may you one more question.

My question is:

When I typed in an invalid name, the survey form is flushed and an error message ("An invalid name") shows up at left bottom of the screen. Is there a way to make the error message show up at other more visible location of the screen?

Thanks a lot!

duta

May 28, 2006, at 2:42 a.m.
0
 

Author Comment

by:duta
ID: 16778666
TO: BogoJoker:
Hi again!

I also wondered whether the error message can be displayed in red.

Thanks again!

duta

May 28, 2006, at 2:54 am
0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16781110
That is what mine does, it centers with red text...
Did you make sure you copied this new line in the CSS?
.err { color: red; margin: 0 auto; text-align: center; }

Now if you do:
<p class="err"><?php echo "<br>$err"; ?></p>

It will do what you want. =)
Joe P
0
 

Author Comment

by:duta
ID: 16782193
TO: BogoJoker:

Thank you so much for your kind help.

Your tip regarding the location of the error message worked just fine.

Thanks again!

duta

May 29, 2006, at 1:19 am
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question