Jump to content

If Statement Redirect?


twilitegxa

Recommended Posts

I have a form that validates with JavaScript, which then redirects to my page that validates with PHP, just in case JavaScript is disabled. I'm having trouble getting it to redirect if there are no PHP or JavaScript errors to my page that inserts it into my table and displays my success message. Can anyone help get my page to redirect properly? Here is my form:

 

<?php 

session_start();

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Web Designs By Liz - Give Your Testimonial</title>

<style type="text/css" media="screen">
/*<![CDATA[*/
@import url(global.css); 
/*]]>*/
</style>

<script type="text/javascript">
//<![CDATA[
<!--
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_nbGroup(event, grpName) { //v6.0
  var i,img,nbArr,args=MM_nbGroup.arguments;
  if (event == "init" && args.length > 2) {
    if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
      img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
      if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
      nbArr[nbArr.length] = img;
      for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
        if (!img.MM_up) img.MM_up = img.src;
        img.src = img.MM_dn = args[i+1];
        nbArr[nbArr.length] = img;
    } }
  } else if (event == "over") {
    document.MM_nbOver = nbArr = new Array();
    for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = (img.MM_dn && args[i+2]) ? args[i+2] : ((args[i+1])? args[i+1] : img.MM_up);
      nbArr[nbArr.length] = img;
    }
  } else if (event == "out" ) {
    for (i=0; i < document.MM_nbOver.length; i++) {
      img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
  } else if (event == "down") {
    nbArr = document[grpName];
    if (nbArr)
      for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
    document[grpName] = nbArr = new Array();
    for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = img.MM_dn = (args[i+1])? args[i+1] : img.MM_up;
      nbArr[nbArr.length] = img;
  } }
}
//-->
//]]>
</script>
<script type="text/javascript" language="JavaScript">
//<![CDATA[
<!--
function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}
//-->
//]]>
</script>
<!-- Validation Script -->
<script type="text/javascript">
function validate_required(field,alerttxt)
{
with (field)
  {
  if (value==null||value=="")
    {
    alert(alerttxt);return false;
    }
  else
    {
    return true;
    }
  }
}

function validate_form(thisform)
{
with (thisform)
  {
  if (validate_required(comment_owner_email,"E-mail address must be filled out!")==false)
  {email.focus();return false;}
  }
}
</script>
<!--End Validation Script -->
</head>
<body onload="MM_preloadImages('home_selected.png','home_hover.png','resume.png','resume_hover.png','resume_selected.png','contact_selected.png','contact_hover.png','portfolio_selected.png','portfolio_hover.png','testimonials.png','testimonials_hover.png','testimonials_selected.png')">
<script language="JavaScript" type="text/javascript">
//<![CDATA[

function doClock() { 
window.setTimeout( "doClock()", 1000 ); 
today = new Date(); 
self.status = today.toString(); 
}
doClock()
//]]>
</script>
<!-- Validation Script -->
<script type="text/javascript">
function validateFormOnSubmit(theForm) {
var reason = "";

  reason += validateUsername(theForm.comment_owner);
  reason += validateEmail(theForm.comment_owner_email);
  reason += validatePhone(theForm.url);
  reason += validateEmpty(theForm.comment);
      
  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }

  //redirect
  window.location = "validation.php"
  return false;
}

function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores

    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "Please enter your name.\n";
    } 
    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 = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "Please enter your e-mail address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid e-mail address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "Your e-mail address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}
function validatePhone(fld) {
      var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
var urlfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var urlFilter = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;

    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "Please enter your web address.\n";
    } else if (!urlFilter.test(urlfld)) {              //test url for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid web address.\n";
    }
    return error;
}
function validateEmpty(fld) {
    var error = "";

    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = "Please enter your comment.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}
</script>
<!--End Validation Script -->
<div class="c1" id="logo"><img src="weblogo.png" title="Web Designs By Liz Logo" alt="Web Designs By Liz Logo" /></div>
<table align="center" border="0" cellpadding="0" cellspacing="0">
<tr>
  <td><a href="index.html" target="_top" onclick="MM_nbGroup('down','group1','home','home_selected.png',1)" onmouseover="MM_nbGroup('over','home','home_hover.png','home_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="home.png" alt="Home Page" name="home" border="0" id="home" /></a></td>
  <td><a href="resume.html" target="_top" onclick="MM_nbGroup('down','group1','resume','resume_selected.png',1)" onmouseover="MM_nbGroup('over','resume','resume_hover.png','resume_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="resume.png" alt="Resume" name="resume" border="0" id="resume" /></a></td>
  <td><a href="contact.html" target="_top" onclick="MM_nbGroup('down','group1','contact','contact_selected.png',1)" onmouseover="MM_nbGroup('over','contact','contact_hover.png','contact_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="contact.png" alt="Contact Page" name="contact" border="0" id="contact" /></a></td>
  <td><a href="portfolio.php" target="_top" onclick="MM_nbGroup('down','group1','portfolio','portfolio_selected.png',1)" onmouseover="MM_nbGroup('over','portfolio','portfolio_hover.png','portfolio_selected.png',1)" onmouseout="MM_nbGroup('out')"><img name="portfolio" src="portfolio.png" border="0" alt="Portfolio" /></a></td>
  <td><a href="testimonials.php" target="_top" onClick="MM_nbGroup('down','group1','testimonials','testimonials_selected.png',1)" onMouseOver="MM_nbGroup('over','testimonials','testimonials_hover.png','testimonials_selected.png',1)" onMouseOut="MM_nbGroup('out')"><img name="testimonials" src="testimonials_selected.png" border="0" alt="Testimonials" onLoad="MM_nbGroup('init','group1','testimonials','testimonials.png',1)" /></a></td>
</tr>
</table>
<div id="resume_title" class="body"><div class="c1"></div>
<table width="900" align="center">
<tr>
<td class="style2" align="center">
<h1>Give Your Testimonial</h1>
</td>
</tr>
<tr>
<td class="style2">
<table class="style2" align="center">
<tr>
<td>
<form name="comment" id="comment" onsubmit="return validateFormOnSubmit(this)" action="" method="post">
<table border="0" cellspacing="0" cellpadding="5" width="662" class="style2">
<tr>
<td align="left"><label for="comment_owner"> Name:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner" id="comment_owner" size="30" /></div>
</td>
</tr>
<tr>
<td align="left"><label for="comment_owner_email">E-mail:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner_email" id="comment_owner_email" size="30" /></div>
</td>
</tr>
<tr>
<td align="left"><label for="url">URL:</label></td>
<td>
<div class="c2"><input type="text" name="url" id="url" size="30" /></div>
</td>
</tr>
<tr>
<td align="left">
<label for="comment">Comments:</label>
</td>
<td>
<textarea name="comment" id="comment" rows="5" cols="30">
</textarea></td>
</tr>
<tr>
<td colspan="4">
<div class="c1"><input name="submit" type="submit" value="Submit" /> <input type="reset" name="reset" id="reset" value="Reset" /></div>
</td>
<td width="2"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div id="footer" class="style2 c1"><br />
<em>Adobe Photoshop, Illustrator, InDesign, Dreamweaver, and Flash logos<br />
are trademarks of Adobe Systems Incorporated.<br />
<br />
Copyright © 2009 Liz Kula. All rights reserved.</em>
<div id="foot-nav">
<ul>
<li><a href="http://validator.w3.org/check?uri=http://webdesignsbyliz.com/resume.html" target="_blank"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a></li>
<li><a href="http://jigsaw.w3.org/css-validator/validator?uri=http://webdesignsbyliz.com/global.css" target="_blank"><img class="c2" src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS!" /></a></li>
</ul>
</div>
</div>
</body>
</html>

 

Here is my PHP validation page:

 

<style type="text/css" media="screen">
/*<![CDATA[*/
@import url(global.css); 
/*]]>*/
</style>
<body onload="MM_preloadImages('home_selected.png','home_hover.png','resume.png','resume_hover.png','resume_selected.png','contact_selected.png','contact_hover.png','portfolio_selected.png','portfolio_hover.png','testimonials.png','testimonials_hover.png','testimonials_selected.png')">
<script language="JavaScript" type="text/javascript">
//<![CDATA[

function doClock() { 
window.setTimeout( "doClock()", 1000 ); 
today = new Date(); 
self.status = today.toString(); 
}
doClock()
//]]>
</script>
<div class="c1" id="logo"><img src="weblogo.png" title="Web Designs By Liz Logo" alt="Web Designs By Liz Logo" /></div>
<table align="center" border="0" cellpadding="0" cellspacing="0">
<tr>
  <td><a href="index.html" target="_top" onclick="MM_nbGroup('down','group1','home','home_selected.png',1)" onmouseover="MM_nbGroup('over','home','home_hover.png','home_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="home.png" alt="Home Page" name="home" border="0" id="home" /></a></td>
  <td><a href="resume.html" target="_top" onclick="MM_nbGroup('down','group1','resume','resume_selected.png',1)" onmouseover="MM_nbGroup('over','resume','resume_hover.png','resume_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="resume.png" alt="Resume" name="resume" border="0" id="resume" /></a></td>
  <td><a href="contact.html" target="_top" onclick="MM_nbGroup('down','group1','contact','contact_selected.png',1)" onmouseover="MM_nbGroup('over','contact','contact_hover.png','contact_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="contact.png" alt="Contact Page" name="contact" border="0" id="contact" /></a></td>
  <td><a href="portfolio.php" target="_top" onclick="MM_nbGroup('down','group1','portfolio','portfolio_selected.png',1)" onmouseover="MM_nbGroup('over','portfolio','portfolio_hover.png','portfolio_selected.png',1)" onmouseout="MM_nbGroup('out')"><img name="portfolio" src="portfolio.png" border="0" alt="Portfolio" /></a></td>
  <td><a href="testimonials.php" target="_top" onClick="MM_nbGroup('down','group1','testimonials','testimonials_selected.png',1)" onMouseOver="MM_nbGroup('over','testimonials','testimonials_hover.png','testimonials_selected.png',1)" onMouseOut="MM_nbGroup('out')"><img name="testimonials" src="testimonials_selected.png" border="0" alt="Testimonials" onLoad="MM_nbGroup('init','group1','testimonials','testimonials.png',1)" /></a></td>
</tr>
</table>
<div id="resume_title" class="body"><div class="c1"></div>
<table width="900" align="center">
<tr>
<td class="style2" align="center">
<h1>Give Your Testimonial</h1>

<?php
/* this is guarunteed to work it is possible to use <? (short tags but this style works everywhere).*/
/*Only verify/validate form when it is submitted program name: form.php */
if(isset($_POST['submit'])){
  $error='';//initialize $error to blank
  if(trim($_POST['comment_owner'])=='' ){
      $error.="Please enter your name!<br />"; //concatenate the $error Message with a line break
  }
  if(trim($_POST['url'])==''){
      $error.="Please enter your web address!<br />";//concatenate more to $error  
  }
  else {
        if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $_POST['url'])) {
        $error.="The URL you entered was not valid!<br />";
        
        }
    }
  if(trim($_POST['comment_owner_email'])==''){
    $error.="Plese enter your e-mail address!<br />";
  }
      else {
        if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $_POST['comment_owner_email'])) {
        $error.="The e-mail you entered was not valid!<br />";
        
        }
    }
    if(trim($_POST['comment'])=='' ){
      $error.="Please enter your comment!<br />"; //concatenate the $error Message with a line break
  }
  if($error==''){//Hmmmm no text is in $error so do something else, the page has verified and the email was valid
  // so uncomment the line below to send the user to your own success page or wherever (swap yourpage.php with your files location).
  header('location:yourpage.php');
  }
    else{
       echo "<span style=color:red>$error</span><br />
       <p>Please press the back button and fill in the form properly and submit again.</p>";
    }                
}
?>

</td>
</tr>
</table>
</div>
<div id="footer" class="style2 c1"><br />
<em>Adobe Photoshop, Illustrator, InDesign, Dreamweaver, and Flash logos<br />
are trademarks of Adobe Systems Incorporated.<br />
<br />
Copyright © 2009 Liz Kula. All rights reserved.</em>
<div id="foot-nav">
<ul>
<li><a href="http://validator.w3.org/check?uri=http://webdesignsbyliz.com/resume.html" target="_blank"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a></li>
<li><a href="http://jigsaw.w3.org/css-validator/validator?uri=http://webdesignsbyliz.com/global.css" target="_blank"><img class="c2" src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS!" /></a></li>
</ul>
</div>
</div>

 

Here is the page that inserts my form results:

 

<?php

//connect to server and select database
$conn = mysql_connect("localhost", "root", "")
    or die(mysql_error());
$db = mysql_select_db("webdes17_testimonials", $conn) or die(mysql_error());

//create and issue the first query
$name=mysql_real_escape_string($_POST['comment_owner']);
$email=mysql_real_escape_string($_POST['comment_owner_email']); 
$url=mysql_real_escape_string($_POST['url']);
$comment=mysql_real_escape_string($_POST['comment']);
$sql="INSERT INTO user_comments (comment_id, comment, comment_create_time, comment_owner, comment_owner_email, url) VALUES ('', '$comment', now(), '$name','$email', '$url')"; 

mysql_query($sql,$conn) or die(mysql_error());

//create nice message for user
$msg = "<p>Your comment has been added. Thank you for your testimonial! You will be redirected to the Testimonials page in a moment. If you aren't forwarded 
to the new page, please click <a href=\"http://www.webdesignsbyliz.com/testimonials.php\">
here</a>. 
</p>";
?>

 

Can anyone help me out? I just need the second page to redirect to the third page if the form has no PHP errors. What am I doing wrong? I also have the third page redirecting to another page automatically after 5 seconds, so I really need the second page to redirect to the third page. can anyone help?

Link to comment
Share on other sites

I don't understand what you mean by line 4. It doesn't seem to make sense to put it on line 4. Can you show me where you mean please about the  _$POST['submit']='submit';? Actually LOL Neither part looked right to me. Because I ready had if ($error=='') with the redirect:

 

if($error==''){
  header('location:yourpage.php');
  }

 

And yes, I have a page named "yourpage.php" for testing purposes. If it redirects, I will change it to the page that inserts the form data. But anyway, can you please show me what you mean and where you made those changes you mentioned because I'm having a hard time understanding what you meant. Thanks!

Link to comment
Share on other sites

The $_POST['submit'] = 'submit' part is to test if the form is submitted or not, basically you get almost the same effect if you use isset($_POST['submit']) inside if statement where you put the condition.

 

Anyway, I don't know why you are making all these pages to submit the form, you need two pages, one contains the form and all the conditions, validation, ..etc, and the second page is the page you need to redirect your first page to.

 

I just noticed that the action attribute in the form tag in your page is empty, I think you should put the page you are submitting the form to or put:

<?php echo $_SERVER['PHP_SELF']; ?> if you are submitting to the same page.

 

good luck!

Link to comment
Share on other sites

Well, I'm still learning PHP, so I don't know how to do everything yet. LOL But the way I learned to insert information from a form into a table is to have the form on one page, then when submitted it goes to the next page that inserts it and display a message. Then I redirect from there because I want it to go back to the viewing page. I'd like to do all the validation one page, but I don't know how exactly. So, my JavaScript works the way it is now, but when I had the action pointing to the insert page, even when the JavaScript gives an error, it would continue to the insert page. So maybe someone can help me out here. I have the form with the JavaScript:

 

<!-- Validation Script -->
<script type="text/javascript">
function validateFormOnSubmit(theForm) {
var reason = "";

  reason += validateUsername(theForm.comment_owner);
  reason += validateEmail(theForm.comment_owner_email);
  reason += validatePhone(theForm.url);
  reason += validateEmpty(theForm.comment);
      
  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }

  //redirect
  window.location = "validation.php"
  return false;
}

function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores

    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "Please enter your name.\n";
    } 
    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 = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "Please enter your e-mail address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid e-mail address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "Your e-mail address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}
function validatePhone(fld) {
      var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
var urlfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var urlFilter = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;

    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "Please enter your web address.\n";
    } else if (!urlFilter.test(urlfld)) {              //test url for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid web address.\n";
    }
    return error;
}
function validateEmpty(fld) {
    var error = "";

    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = "Please enter your comment.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}
</script>
<!--End Validation Script -->
<form name="comment" id="comment" onsubmit="return validateFormOnSubmit(this)" action="" method="post">
<table border="0" cellspacing="0" cellpadding="5" width="662" class="style2">
<tr>
<td align="left"><label for="comment_owner"> Name:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner" id="comment_owner" size="30" /></div>
</td>
</tr>
<tr>
<td align="left"><label for="comment_owner_email">E-mail:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner_email" id="comment_owner_email" size="30" /></div>
</td>
</tr>
<tr>
<td align="left"><label for="url">URL:</label></td>
<td>
<div class="c2"><input type="text" name="url" id="url" size="30" /></div>
</td>
</tr>
<tr>
<td align="left">
<label for="comment">Comments:</label>
</td>
<td>
<textarea name="comment" id="comment" rows="5" cols="30">
</textarea></td>
</tr>
<tr>
<td colspan="4">
<div class="c1"><input name="submit" type="submit" value="Submit" /> <input type="reset" name="reset" id="reset" value="Reset" /></div>
</td>
<td width="2"></td>
</tr>
</table>
</form>

 

But how can I put my PHP validation and insert statement and message all on the same page? Here is my PHP validation:

 

<?php
if(isset($_POST['submit'])){
  $error='';//initialize $error to blank
  if(trim($_POST['comment_owner'])=='' ){
      $error.="Please enter your name!<br />"; //concatenate the $error Message with a line break
  }
  if(trim($_POST['url'])==''){
      $error.="Please enter your web address!<br />";//concatenate more to $error  
  }
  else {
        if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $_POST['url'])) {
        $error.="The URL you entered was not valid!<br />";
        
        }
    }
  if(trim($_POST['comment_owner_email'])==''){
    $error.="Plese enter your e-mail address!<br />";
  }
      else {
        if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $_POST['comment_owner_email'])) {
        $error.="The e-mail you entered was not valid!<br />";
        
        }
    }
    if(trim($_POST['comment'])=='' ){
      $error.="Please enter your comment!<br />"; //concatenate the $error Message with a line break
  }
  if($error=='')
  header('location:yourpage.php');
  }
    else{
       echo "<span style=color:red>$error</span><br />
       <p>Please press the back button and fill in the form properly and submit again.</p>";
    }                
}
?>

 

And here is my insert page:

 

<?php

//connect to server and select database
$conn = mysql_connect("localhost", "webdes17_twilite", "minimoon")
    or die(mysql_error());
$db = mysql_select_db("webdes17_testimonials", $conn) or die(mysql_error());

//create and issue the first query
$name=mysql_real_escape_string($_POST['comment_owner']);
$email=mysql_real_escape_string($_POST['comment_owner_email']); 
$url=mysql_real_escape_string($_POST['url']);
$comment=mysql_real_escape_string($_POST['comment']);
$sql="INSERT INTO user_comments (comment_id, comment, comment_create_time, comment_owner, comment_owner_email, url) VALUES ('', '$comment', now(), '$name','$email', '$url')"; 

mysql_query($sql,$conn) or die(mysql_error());

//create nice message for user
$msg = "<p>Your comment has been added. Thank you for your testimonial! You will be redirected to the Testimonials page in a moment. If you aren't forwarded 
to the new page, please click <a href=\"http://www.webdesignsbyliz.com/testimonials.php\">
here</a>. 
</p>";
?>

 

Right now, these are three separate pages. How can I put the PHP validation and insert statement on the same page? Would I use an if statement? How would I write it? Can anyone help? Or are you saying that ALL teh validation can go on one page, the same page as the form? Can someone please help me?

Link to comment
Share on other sites

Ok, great that you are learning and I got you before you get used to coding with bad habits like this one lol.

 

Putting the form and the condition, validation, ..etc in two different pages is not necessarily wrong, however its a bad practice.

 

Here is a simple way to understand the concept of putting them all in one page which gives much more flexibility and advantages :

<?php
// if the form is submitted which means that this is not the first time visit for this user, 
// the user did put all values and hit the submit button and inside this if statement we do what we 
//want to happen in the second page in your code
if ($_POST['submit']) {

   // grab the data from the $_POST array and put it in a variables
// $email = $_POST['email'];
  // validate the data and make sure they are all correct or have a value or whatever
  // send the data to the database and check if its entered successfully
// don't forget the error handling here, you might wanna see if the data was entered or not
// do NOT print any thing before redirecting otherwise it won't work, so you collect the errors here and display them right before the form if there is any errors 

// NOW redirect

} else {
// this means the form is NOT submitted and the user is visiting this page for the
// first time (not a submitted page because $_POST['submit'] doesn't have a value
//display the form right here, you might want to cut off the php tags here and start html but
// don't forget the last curly brace of else and also don't forget to initialize variables to fill 
// the form with them because you don't want the user to submit all the data again if he
// had just one error
//so do like this in the php

$email = '';

and in html do this
<input type="text" name="email" value="<?php echo $email; ?>" /> 

}

 

Good luck, and ask if you get stuck, lol.

Link to comment
Share on other sites

Hey, this code doesn't include the explanation how you will be doing the Java Script part, I am talking about PHP only, I suggest you do the checking in PHP because people might have Java script turned off in their browsers or you can do do both JS and PHP, whatever you like!

 

Good luck!

Link to comment
Share on other sites

oh replace this line in your html

<form name="comment" id="comment" onsubmit="return validateFormOnSubmit(this)" action="" method="post">

with this one

<form name="comment" id="comment" onsubmit="return validateFormOnSubmit(this)" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

this is if you want to follow the approach I explained to you!

Link to comment
Share on other sites

I will try your example and I will probably add the JavaScript that I have working and see how that goes because I want to accommodate both client-side as well as server-side validation, just in case JavaScript is disable, as you pointed out. I will be back if I get stuck! LOL

Link to comment
Share on other sites

Okay, I need a little bit of help still. I have everything on one page now, except for the JavaScript, but I will add it in later, after I get the PHP working properly. Okay, so I have it set up like this:

 

<?php

//connect to server and select database
$conn = mysql_connect("localhost", "root", "")
    or die(mysql_error());
$db = mysql_select_db("smrpg", $conn) or die(mysql_error());

// if the form is submitted which means that this is not the first time visit for this user, 
// the user did put all values and hit the submit button and inside this if statement we do what we 
//want to happen in the second page in your code
if (isset($_POST['submit'])) {

//create and issue the first query
$name=mysql_real_escape_string($_POST['comment_owner']);
$email=mysql_real_escape_string($_POST['comment_owner_email']); 
$url=mysql_real_escape_string($_POST['url']);
$comment=mysql_real_escape_string($_POST['comment']);

$error='';//initialize $error to blank
  if(trim($_POST['comment_owner'])=='' ){
      $error.="Please enter your name!<br />"; //concatenate the $error Message with a line break
  }
  if(trim($_POST['url'])==''){
      $error.="Please enter your web address!<br />";//concatenate more to $error  
  }
  else {
        if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $_POST['url'])) {
        $error.="The URL you entered was not valid!<br />";
        
        }
    }
  if(trim($_POST['comment_owner_email'])==''){
    $error.="Plese enter your e-mail address!<br />";
  }
      else {
        if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $_POST['comment_owner_email'])) {
        $error.="The e-mail you entered was not valid!<br />";
        
        }
    }
    if(trim($_POST['comment'])=='' ){
      $error.="Please enter your comment!<br />"; //concatenate the $error Message with a line break
  }
  if($error==''){
  header( 'Location: testimonials.php' ) ;
  }
    else{
       echo "<span style=color:red>$error</span><br />
       <p>Please press the back button and fill in the form properly and submit again.</p>";
    }     
    
    $sql="INSERT INTO user_comments (comment_id, comment, comment_create_time, comment_owner, comment_owner_email, url) VALUES ('', '$comment', now(), '$name','$email', '$url')"; 

mysql_query($sql,$conn) or die(mysql_error());



   // grab the data from the $_POST array and put it in a variables
// $email = $_POST['email'];
  // validate the data and make sure they are all correct or have a value or whatever
  // send the data to the database and check if its entered successfully
// don't forget the error handling here, you might wanna see if the data was entered or not
// do NOT print any thing before redirecting otherwise it won't work, so you collect the errors here and display them right before the form if there is any errors 

// NOW redirect

} else {
// this means the form is NOT submitted and the user is visiting this page for the
// first time (not a submitted page because $_POST['submit'] doesn't have a value
//display the form right here, you might want to cut off the php tags here and start html but
// don't forget the last curly brace of else and also don't forget to initialize variables to fill 
// the form with them because you don't want the user to submit all the data again if he
// had just one error
//so do like this in the php

$name= '';
$email= '';
$url= '';
$comment= '';
}
?>

<form name="comment" id="comment" onsubmit="return validateFormOnSubmit(this)" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0" cellspacing="0" cellpadding="5" width="662" class="style2">
<tr>
<td align="left"><label for="name"> Name:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner" id="comment_owner" size="30" value="<?php echo $name; ?>"/></div>
</td>
</tr>
<tr>
<td align="left"><label for="email">E-mail:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner_email" id="comment_owner_email" size="30" value="<?php echo $email; ?>"/></div>
</td>
</tr>
<tr>
<td align="left"><label for="url">URL:</label></td>
<td>
<div class="c2"><input type="text" name="url" id="url" size="30" value="<?php echo $url; ?>"/></div>
</td>
</tr>
<tr>
<td align="left">
<label for="comment">Comments:</label>
</td>
<td>
<textarea name="comment" id="comment" rows="5" cols="30" value="<?php echo $comment; ?>">
</textarea></td>
</tr>
<tr>
<td colspan="4">
<div class="c1"><input name="submit" type="submit" value="Submit" /> <input type="reset" name="reset" id="reset" value="Reset" /></div>
</td>
<td width="2"></td>
</tr>
</table>
</form>

 

But whenever I fill in one of the fields incorrectly and submit to check if my validation is working, it doesn't redirect (like it's supposed to), and the errors are showing (like they are supposed to), but each time submit is pressed, it is still inserting the data, even without the fields being properly filled in. Where is my insert statement supposed to go? I thought it went inside the first if statement, like if all validation passes, insert data, if not, show form with posted data pre-filled. Also, that pre-filled part is working also, so that's good. :-) Can you help me with where the insert statement is supposed to go, please? Also, I think I need to modify the if/else statement that says "Press back button on your browser, etc" because I don't need it to say anything, sinec the error messages display if there is an error present, but how do I write that if statement to where it displays the errors if there are any but redirects if there aren't any? I think I've got it a little mixed up.

Link to comment
Share on other sites

<?php

//connect to server and select database
$conn = mysql_connect("localhost", "root", "")
    or die(mysql_error());
$db = mysql_select_db("smrpg", $conn) or die(mysql_error());

// if the form is submitted which means that this is not the first time visit for this user, 
// the user did put all values and hit the submit button and inside this if statement we do what we 
//want to happen in the second page in your code
if (isset($_POST['submit'])) {

//create and issue the first query
$name=mysql_real_escape_string($_POST['comment_owner']);
$email=mysql_real_escape_string($_POST['comment_owner_email']); 
$url=mysql_real_escape_string($_POST['url']);
$comment=mysql_real_escape_string($_POST['comment']);

$error='';//initialize $error to blank
  if(trim($_POST['comment_owner'])=='' ){
      $error.="Please enter your name!<br />"; //concatenate the $error Message with a line break
  }
  if(trim($_POST['url'])==''||empty($_POST['url'])){
      $error.="Please enter your web address!<br />";//concatenate more to $error  
  }
  else {
        if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $_POST['url'])) {
        $error.="The URL you entered was not valid!<br />";
        
        }
    }
  if(trim($_POST['comment_owner_email'])==''||empty($_POST['comment_owner_email'])){
    $error.="Plese enter your e-mail address!<br />";
  }
      else {
        if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $_POST['comment_owner_email'])) {
        $error.="The e-mail you entered was not valid!<br />";
        
        }
    }
    if(trim($_POST['comment'])==''||empty($_POST['comment'])){
      $error.="Please enter your comment!<br />"; //concatenate the $error Message with a line break
  }
  if($error==''||empty($error)){
  header( 'Location: testimonials.php' ) ;
  }
    else{
       echo "<span style=color:red>$error</span><br />
       <p>Please press the back button and fill in the form properly and submit again.</p>";
    }     
    
    $sql="INSERT INTO user_comments (comment_id, comment, comment_create_time, comment_owner, comment_owner_email, url) VALUES ('', '$comment', now(), '$name','$email', '$url')"; 

mysql_query($sql,$conn) or die(mysql_error());



   // grab the data from the $_POST array and put it in a variables
// $email = $_POST['email'];
  // validate the data and make sure they are all correct or have a value or whatever
  // send the data to the database and check if its entered successfully
// don't forget the error handling here, you might wanna see if the data was entered or not
// do NOT print any thing before redirecting otherwise it won't work, so you collect the errors here and display them right before the form if there is any errors 

// NOW redirect

} else {
// this means the form is NOT submitted and the user is visiting this page for the
// first time (not a submitted page because $_POST['submit'] doesn't have a value
//display the form right here, you might want to cut off the php tags here and start html but
// don't forget the last curly brace of else and also don't forget to initialize variables to fill 
// the form with them because you don't want the user to submit all the data again if he
// had just one error
//so do like this in the php

$name= '';
$email= '';
$url= '';
$comment= '';
}
?>

<form name="comment" id="comment" onsubmit="return validateFormOnSubmit(this)" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0" cellspacing="0" cellpadding="5" width="662" class="style2">
<tr>
<td align="left"><label for="name"> Name:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner" id="comment_owner" size="30" value="<?php echo $name; ?>"/></div>
</td>
</tr>
<tr>
<td align="left"><label for="email">E-mail:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner_email" id="comment_owner_email" size="30" value="<?php echo $email; ?>"/></div>
</td>
</tr>
<tr>
<td align="left"><label for="url">URL:</label></td>
<td>
<div class="c2"><input type="text" name="url" id="url" size="30" value="<?php echo $url; ?>"/></div>
</td>
</tr>
<tr>
<td align="left">
<label for="comment">Comments:</label>
</td>
<td>
<textarea name="comment" id="comment" rows="5" cols="30" value="<?php echo $comment; ?>">
</textarea></td>
</tr>
<tr>
<td colspan="4">
<div class="c1"><input name="submit" type="submit" value="Submit" /> <input type="reset" name="reset" id="reset" value="Reset" /></div>
</td>
<td width="2"></td>
</tr>
</table>
</form>

 

i added empty() along with $error=='' hope that helps abit  :-\

Link to comment
Share on other sites

Well, I figured out the part about the insert statement. I had to add it to the if part where it redirects.

 

if($error==''){
  header( 'Location: testimonials.php' ) ;
  $sql="INSERT INTO user_comments (comment_id, comment, comment_create_time, comment_owner, comment_owner_email, url) VALUES ('', '$comment', now(), '$name','$email', '$url')"; 

mysql_query($sql,$conn) or die(mysql_error());
  }
    else{
       echo "<span style=color:red>$error</span><br />";
    }     

 

Now I just need to try adding in my JavaScript and test it. Thanks for all the help guys!

 

 

Link to comment
Share on other sites

:-( When I tried to upload this code to my server, I got this error when the form is submitted:

 

Warning: Cannot modify header information - headers already sent by (output started at testimonials_form.php:7) in testimonials_form.php on line 237

 

Also, when this error occurs, all the fields are pre-filled in except for my comment. I think that might be a problem for someone if they got an error and they had written a lot in the comment field. Can you guys help?

Link to comment
Share on other sites

Here is what I have for that page with the error:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Web Designs By Liz - Testimonials</title>

<style type="text/css" media="screen">
/*<![CDATA[*/
@import url(global.css); 
/*]]>*/
</style>

<script type="text/javascript">
//<![CDATA[
<!--
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_nbGroup(event, grpName) { //v6.0
  var i,img,nbArr,args=MM_nbGroup.arguments;
  if (event == "init" && args.length > 2) {
    if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
      img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
      if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
      nbArr[nbArr.length] = img;
      for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
        if (!img.MM_up) img.MM_up = img.src;
        img.src = img.MM_dn = args[i+1];
        nbArr[nbArr.length] = img;
    } }
  } else if (event == "over") {
    document.MM_nbOver = nbArr = new Array();
    for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = (img.MM_dn && args[i+2]) ? args[i+2] : ((args[i+1])? args[i+1] : img.MM_up);
      nbArr[nbArr.length] = img;
    }
  } else if (event == "out" ) {
    for (i=0; i < document.MM_nbOver.length; i++) {
      img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
  } else if (event == "down") {
    nbArr = document[grpName];
    if (nbArr)
      for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
    document[grpName] = nbArr = new Array();
    for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = img.MM_dn = (args[i+1])? args[i+1] : img.MM_up;
      nbArr[nbArr.length] = img;
  } }
}
//-->
//]]>
</script>
<script type="text/javascript" language="JavaScript">
//<![CDATA[
<!--
function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}
//-->
//]]>
</script>
<!-- Validation Script -->
<script type="text/javascript">
function validateFormOnSubmit(theForm) {
var reason = "";

  reason += validateUsername(theForm.comment_owner);
  reason += validateEmail(theForm.comment_owner_email);
  reason += validatePhone(theForm.url);
  reason += validateEmpty(theForm.comment);
      
  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }

}

function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores

    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "Please enter your name.\n";
    } 
    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 = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "Please enter your e-mail address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid e-mail address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "Your e-mail address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}
function validatePhone(fld) {
      var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
var urlfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var urlFilter = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;

    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "Please enter your web address.\n";
    } else if (!urlFilter.test(urlfld)) {              //test url for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid web address.\n";
    }
    return error;
}
function validateEmpty(fld) {
    var error = "";

    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = "Please enter your comment.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}
</script>
<!--End Validation Script -->
</head>
<body onload="MM_preloadImages('home_selected.png','home_hover.png','resume.png','resume_hover.png','resume_selected.png','contact_selected.png','contact_hover.png','portfolio_selected.png','portfolio_hover.png')">
<script language="JavaScript" type="text/javascript">
//<![CDATA[

function doClock() { 
window.setTimeout( "doClock()", 1000 ); 
today = new Date(); 
self.status = today.toString(); 
}
doClock()
//]]>
</script>
<div class="c1" id="logo"><img src="weblogo.png" title="Web Designs By Liz Logo" alt="Web Designs By Liz Logo" /></div>
<table align="center" border="0" cellpadding="0" cellspacing="0">
<tr>
<td><a href="index.html" target="_top" onclick="MM_nbGroup('down','group1','home','home_selected.png',1)" onmouseover="MM_nbGroup('over','home','home_hover.png','home_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="home.png" alt="Home Page" name="home" border="0" id="home" /></a></td>
<td><a href="resume.html" target="_top" onclick="MM_nbGroup('down','group1','resume','resume_selected.png',1)" onmouseover="MM_nbGroup('over','resume','resume_hover.png','resume_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="resume.png" alt="Resume" name="resume" border="0" id="resume" /></a></td>
<td><a href="contact.html" target="_top" onclick="MM_nbGroup('down','group1','contact','contact_selected.png',1)" onmouseover="MM_nbGroup('over','contact','contact_hover.png','contact_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="contact.png" alt="Contact Page" name="contact" border="0" id="contact" /></a></td>
<td><a href="portfolio.php" target="_top" onclick="MM_nbGroup('down','group1','portfolio','portfolio_selected.png',1)" onmouseover="MM_nbGroup('over','portfolio','portfolio_hover.png','portfolio_selected.png',1)" onmouseout="MM_nbGroup('out')"><img name="portfolio" src="portfolio.png" border="0" alt="Portfolio" /></a></td>
<td><a href="testimonials.php" target="_top" onclick="MM_nbGroup('down','group1','testimonials','testimonials_selected.png',1)" onmouseover="MM_nbGroup('over','testimonials','testimonials_hover.png','testimonials_selected.png',1)" onmouseout="MM_nbGroup('out')"><img name="testimonials" src="testimonials_selected.png" border="0" alt="Testimonials" /></a></td>
</tr>
</table>
<div id="resume_title" class="body"><div class="c1"></div>
<table width="900" align="center">
<tr>
<td class="style2" align="center">
<h1>Give Your Testimonial</h1>
</td>
</tr>
<tr>
<td class="style2">
<table class="style2" align="center">
<tr>
<td>
<?php

//connect to server and select database
$conn = mysql_connect("localhost", "webdes17_twilite", "minimoon")
    or die(mysql_error());
$db = mysql_select_db("webdes17_testimonials", $conn) or die(mysql_error());

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

//create and issue the first query
$name=mysql_real_escape_string($_POST['comment_owner']);
$email=mysql_real_escape_string($_POST['comment_owner_email']); 
$url=mysql_real_escape_string($_POST['url']);
$comment=mysql_real_escape_string($_POST['comment']);

$error='';//initialize $error to blank
  if(trim($_POST['comment_owner'])=='' ){
      $error.="Please enter your name!<br />"; //concatenate the $error Message with a line break
  }
  if(trim($_POST['url'])==''){
      $error.="Please enter your web address!<br />";//concatenate more to $error  
  }
  else {
        if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $_POST['url'])) {
        $error.="The URL you entered was not valid!<br />";
        
        }
    }
  if(trim($_POST['comment_owner_email'])==''){
    $error.="Plese enter your e-mail address!<br />";
  }
      else {
        if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $_POST['comment_owner_email'])) {
        $error.="The e-mail you entered was not valid!<br />";
        
        }
    }
    if(trim($_POST['comment'])=='' ){
      $error.="Please enter your comment!<br />"; //concatenate the $error Message with a line break
  }
  if($error==''){
  header( 'Location: testimonials.php' ) ;
  $sql="INSERT INTO user_comments (comment_id, comment, comment_create_time, comment_owner, comment_owner_email, url) VALUES ('', '$comment', now(), '$name','$email', '$url')"; 

mysql_query($sql,$conn) or die(mysql_error());
  }
    else{
       echo "<span style=color:red>$error</span><br />";
    }    
} else {

$name= '';
$email= '';
$url= '';
$comment= '';
}
?>

<form name="comment" id="comment" onsubmit="return validateFormOnSubmit(this)" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0" cellspacing="0" cellpadding="5" width="662" class="style2">
<tr>
<td align="left"><label for="name"> Name:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner" id="comment_owner" size="30" value="<?php echo $name; ?>"/></div>
</td>
</tr>
<tr>
<td align="left"><label for="email">E-mail:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner_email" id="comment_owner_email" size="30" value="<?php echo $email; ?>"/></div>
</td>
</tr>
<tr>
<td align="left"><label for="url">URL:</label></td>
<td>
<div class="c2"><input type="text" name="url" id="url" size="30" value="<?php echo $url; ?>"/></div>
</td>
</tr>
<tr>
<td align="left">
<label for="comment">Comments:</label>
</td>
<td>
<textarea name="comment" id="comment" rows="5" cols="30" value="<?php echo $comment; ?>">
</textarea></td>
</tr>
<tr>
<td colspan="4">
<div class="c1"><input name="submit" type="submit" value="Submit" /> <input type="reset" name="reset" id="reset" value="Reset" /></div>
</td>
<td width="2"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div id="footer" class="style2 c1"><br />
<em>Adobe Photoshop, Illustrator, InDesign, Dreamweaver, and Flash logos<br />
are trademarks of Adobe Systems Incorporated.<br />
<br />
Copyright © 2009 Liz Kula. All rights reserved.</em>
<div id="foot-nav">
<ul>
<li><a href="http://validator.w3.org/check?uri=http://webdesignsbyliz.com/resume.html" target="_blank"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a></li>
<li><a href="http://jigsaw.w3.org/css-validator/validator?uri=http://webdesignsbyliz.com/global.css" target="_blank"><img class="c2" src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS!" /></a></li>
</ul>
</div>
</div>
</body>
</html>

Link to comment
Share on other sites

try puting exit; after your header/redirect

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Web Designs By Liz - Testimonials</title>

<style type="text/css" media="screen">
/*<![CDATA[*/
@import url(global.css);
/*]]>*/
</style>

<script type="text/javascript">
//<![CDATA[
<!--
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_nbGroup(event, grpName) { //v6.0
  var i,img,nbArr,args=MM_nbGroup.arguments;
  if (event == "init" && args.length > 2) {
    if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
      img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
      if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
      nbArr[nbArr.length] = img;
      for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
        if (!img.MM_up) img.MM_up = img.src;
        img.src = img.MM_dn = args[i+1];
        nbArr[nbArr.length] = img;
    } }
  } else if (event == "over") {
    document.MM_nbOver = nbArr = new Array();
    for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = (img.MM_dn && args[i+2]) ? args[i+2] : ((args[i+1])? args[i+1] : img.MM_up);
      nbArr[nbArr.length] = img;
    }
  } else if (event == "out" ) {
    for (i=0; i < document.MM_nbOver.length; i++) {
      img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
  } else if (event == "down") {
    nbArr = document[grpName];
    if (nbArr)
      for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
    document[grpName] = nbArr = new Array();
    for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = img.MM_dn = (args[i+1])? args[i+1] : img.MM_up;
      nbArr[nbArr.length] = img;
  } }
}
//-->
//]]>
</script>
<script type="text/javascript" language="JavaScript">
//<![CDATA[
<!--
function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}
//-->
//]]>
</script>
<!-- Validation Script -->
<script type="text/javascript">
function validateFormOnSubmit(theForm) {
var reason = "";

  reason += validateUsername(theForm.comment_owner);
  reason += validateEmail(theForm.comment_owner_email);
  reason += validatePhone(theForm.url);
  reason += validateEmpty(theForm.comment);
     
  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }

}

function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores

    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "Please enter your name.\n";
    }
    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 = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "Please enter your e-mail address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid e-mail address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "Your e-mail address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}
function validatePhone(fld) {
      var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
var urlfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var urlFilter = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;

    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "Please enter your web address.\n";
    } else if (!urlFilter.test(urlfld)) {              //test url for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid web address.\n";
    }
    return error;
}
function validateEmpty(fld) {
    var error = "";

    if (fld.value.length == 0) {
        fld.style.background = 'Yellow';
        error = "Please enter your comment.\n"
    } else {
        fld.style.background = 'White';
    }
    return error; 
}
</script>
<!--End Validation Script -->
</head>
<body onload="MM_preloadImages('home_selected.png','home_hover.png','resume.png','resume_hover.png','resume_selected.png','contact_selected.png','contact_hover.png','portfolio_selected.png','portfolio_hover.png')">
<script language="JavaScript" type="text/javascript">
//<![CDATA[

function doClock() {
window.setTimeout( "doClock()", 1000 );
today = new Date();
self.status = today.toString();
}
doClock()
//]]>
</script>
<div class="c1" id="logo"><img src="weblogo.png" title="Web Designs By Liz Logo" alt="Web Designs By Liz Logo" /></div>
<table align="center" border="0" cellpadding="0" cellspacing="0">
<tr>
<td><a href="index.html" target="_top" onclick="MM_nbGroup('down','group1','home','home_selected.png',1)" onmouseover="MM_nbGroup('over','home','home_hover.png','home_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="home.png" alt="Home Page" name="home" border="0" id="home" /></a></td>
<td><a href="resume.html" target="_top" onclick="MM_nbGroup('down','group1','resume','resume_selected.png',1)" onmouseover="MM_nbGroup('over','resume','resume_hover.png','resume_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="resume.png" alt="Resume" name="resume" border="0" id="resume" /></a></td>
<td><a href="contact.html" target="_top" onclick="MM_nbGroup('down','group1','contact','contact_selected.png',1)" onmouseover="MM_nbGroup('over','contact','contact_hover.png','contact_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="contact.png" alt="Contact Page" name="contact" border="0" id="contact" /></a></td>
<td><a href="portfolio.php" target="_top" onclick="MM_nbGroup('down','group1','portfolio','portfolio_selected.png',1)" onmouseover="MM_nbGroup('over','portfolio','portfolio_hover.png','portfolio_selected.png',1)" onmouseout="MM_nbGroup('out')"><img name="portfolio" src="portfolio.png" border="0" alt="Portfolio" /></a></td>
<td><a href="testimonials.php" target="_top" onclick="MM_nbGroup('down','group1','testimonials','testimonials_selected.png',1)" onmouseover="MM_nbGroup('over','testimonials','testimonials_hover.png','testimonials_selected.png',1)" onmouseout="MM_nbGroup('out')"><img name="testimonials" src="testimonials_selected.png" border="0" alt="Testimonials" /></a></td>
</tr>
</table>
<div id="resume_title" class="body"><div class="c1"></div>
<table width="900" align="center">
<tr>
<td class="style2" align="center">
<h1>Give Your Testimonial</h1>
</td>
</tr>
<tr>
<td class="style2">
<table class="style2" align="center">
<tr>
<td>
<?php

//connect to server and select database
$conn = mysql_connect("localhost", "webdes17_twilite", "minimoon")
    or die(mysql_error());
$db = mysql_select_db("webdes17_testimonials", $conn) or die(mysql_error());

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

//create and issue the first query
$name=mysql_real_escape_string($_POST['comment_owner']);
$email=mysql_real_escape_string($_POST['comment_owner_email']); 
$url=mysql_real_escape_string($_POST['url']);
$comment=mysql_real_escape_string($_POST['comment']);

$error='';//initialize $error to blank
  if(trim($_POST['comment_owner'])=='' ){
      $error.="Please enter your name!<br />"; //concatenate the $error Message with a line break
  }
  if(trim($_POST['url'])==''){
      $error.="Please enter your web address!<br />";//concatenate more to $error  
  }
  else {
        if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $_POST['url'])) {
        $error.="The URL you entered was not valid!<br />";
        
        }
    }
  if(trim($_POST['comment_owner_email'])==''){
    $error.="Plese enter your e-mail address!<br />";
  }
      else {
        if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $_POST['comment_owner_email'])) {
        $error.="The e-mail you entered was not valid!<br />";
        
        }
    }
    if(trim($_POST['comment'])=='' ){
      $error.="Please enter your comment!<br />"; //concatenate the $error Message with a line break
  }
  if($error==''){
  	  $sql="INSERT INTO user_comments (comment_id, comment, comment_create_time, comment_owner, comment_owner_email, url) VALUES ('', '$comment', now(), '$name','$email', '$url')"; 

mysql_query($sql,$conn) or die(mysql_error());
  header( 'Location: testimonials.php' ) ;
  exit;
  }
    else{
       echo "<span style=color:red>$error</span><br />";
    }    
} else {

$name= '';
$email= '';
$url= '';
$comment= '';
}
?>

<form name="comment" id="comment" onsubmit="return validateFormOnSubmit(this)" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0" cellspacing="0" cellpadding="5" width="662" class="style2">
<tr>
<td align="left"><label for="name"> Name:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner" id="comment_owner" size="30" value="<?php echo $name; ?>"/></div>
</td>
</tr>
<tr>
<td align="left"><label for="email">E-mail:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner_email" id="comment_owner_email" size="30" value="<?php echo $email; ?>"/></div>
</td>
</tr>
<tr>
<td align="left"><label for="url">URL:</label></td>
<td>
<div class="c2"><input type="text" name="url" id="url" size="30" value="<?php echo $url; ?>"/></div>
</td>
</tr>
<tr>
<td align="left">
<label for="comment">Comments:</label>
</td>
<td>
<textarea name="comment" id="comment" rows="5" cols="30" value="<?php echo $comment; ?>">
</textarea></td>
</tr>
<tr>
<td colspan="4">
<div class="c1"><input name="submit" type="submit" value="Submit" /> <input type="reset" name="reset" id="reset" value="Reset" /></div>
</td>
<td width="2"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div id="footer" class="style2 c1"><br />
<em>Adobe Photoshop, Illustrator, InDesign, Dreamweaver, and Flash logos<br />
are trademarks of Adobe Systems Incorporated.<br />
<br />
Copyright © 2009 Liz Kula. All rights reserved.</em>
<div id="foot-nav">
<ul>
<li><a href="http://validator.w3.org/check?uri=http://webdesignsbyliz.com/resume.html" target="_blank"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a></li>
<li><a href="http://jigsaw.w3.org/css-validator/validator?uri=http://webdesignsbyliz.com/global.css" target="_blank"><img class="c2" src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS!" /></a></li>
</ul>
</div>
</div>
</body>
</html>

 

or if that doesn't work to your liking just put ob_start() at the top of your code it is not a permanent solution though.

Link to comment
Share on other sites

I tried putting the php script before my html script since you can't have anything in the browser before the header redirect thing, and I just put a div tag around the error messages and used css to display them where I wanted, and that worked fine. Here is the revised code:

 

<?php

//connect to server and select database
$conn = mysql_connect("localhost", "webdes17_twilite", "minimoon")
    or die(mysql_error());
$db = mysql_select_db("webdes17_testimonials", $conn) or die(mysql_error());

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

//create and issue the first query
$name=mysql_real_escape_string($_POST['comment_owner']);
$email=mysql_real_escape_string($_POST['comment_owner_email']); 
$url=mysql_real_escape_string($_POST['url']);
$comment=mysql_real_escape_string($_POST['comment']);

$error='';//initialize $error to blank
  if(trim($_POST['comment_owner'])=='' ){
      $error.="Please enter your name!<br />"; //concatenate the $error Message with a line break
  }
  if(trim($_POST['url'])==''){
      $error.="Please enter your web address!<br />";//concatenate more to $error  
  }
  else {
        if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $_POST['url'])) {
        $error.="The URL you entered was not valid!<br />";
        
        }
    }
  if(trim($_POST['comment_owner_email'])==''){
    $error.="Plese enter your e-mail address!<br />";
  }
      else {
        if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $_POST['comment_owner_email'])) {
        $error.="The e-mail you entered was not valid!<br />";
        
        }
    }
    if(trim($_POST['comment'])=='' ){
      $error.="Please enter your comment!<br />"; //concatenate the $error Message with a line break
  }
  if($error==''){
  header( 'Location: testimonials.php' ) ;
  $sql="INSERT INTO user_comments (comment_id, comment, comment_create_time, comment_owner, comment_owner_email, url) VALUES ('', '$comment', now(), '$name','$email', '$url')"; 

mysql_query($sql,$conn) or die(mysql_error());
  }
    else{
       echo "<div class=error><span style=color:red>$error</span><br /></div>";
    }    
} else {

$name= '';
$email= '';
$url= '';
$comment= '';
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Web Designs By Liz - Testimonials</title>

<style type="text/css" media="screen">
/*<![CDATA[*/
@import url(global.css); 
/*]]>*/
</style>

<script type="text/javascript">
//<![CDATA[
<!--
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_nbGroup(event, grpName) { //v6.0
  var i,img,nbArr,args=MM_nbGroup.arguments;
  if (event == "init" && args.length > 2) {
    if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
      img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
      if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
      nbArr[nbArr.length] = img;
      for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
        if (!img.MM_up) img.MM_up = img.src;
        img.src = img.MM_dn = args[i+1];
        nbArr[nbArr.length] = img;
    } }
  } else if (event == "over") {
    document.MM_nbOver = nbArr = new Array();
    for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = (img.MM_dn && args[i+2]) ? args[i+2] : ((args[i+1])? args[i+1] : img.MM_up);
      nbArr[nbArr.length] = img;
    }
  } else if (event == "out" ) {
    for (i=0; i < document.MM_nbOver.length; i++) {
      img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
  } else if (event == "down") {
    nbArr = document[grpName];
    if (nbArr)
      for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
    document[grpName] = nbArr = new Array();
    for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = img.MM_dn = (args[i+1])? args[i+1] : img.MM_up;
      nbArr[nbArr.length] = img;
  } }
}
//-->
//]]>
</script>
<script type="text/javascript" language="JavaScript">
//<![CDATA[
<!--
function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}
//-->
//]]>
</script>
<!-- Validation Script -->
<script type="text/javascript">
function validateFormOnSubmit(theForm) {
var reason = "";

  reason += validateUsername(theForm.comment_owner);
  reason += validateEmail(theForm.comment_owner_email);
  reason += validatePhone(theForm.url);
  reason += validateEmpty(theForm.comment);
      
  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }

}

function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores

    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "Please enter your name.\n";
    } 
    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 = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "Please enter your e-mail address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid e-mail address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "Your e-mail address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}
function validatePhone(fld) {
      var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
var urlfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var urlFilter = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;

    if (fld.value == "") {
        fld.style.background = 'Yellow'; 
        error = "Please enter your web address.\n";
    } else if (!urlFilter.test(urlfld)) {              //test url for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid web address.\n";
    }
    return error;
}
function validateEmpty(fld) {
    var error = "";

    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = "Please enter your comment.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}
</script>
<!--End Validation Script -->
</head>
<body onload="MM_preloadImages('home_selected.png','home_hover.png','resume.png','resume_hover.png','resume_selected.png','contact_selected.png','contact_hover.png','portfolio_selected.png','portfolio_hover.png')">
<script language="JavaScript" type="text/javascript">
//<![CDATA[

function doClock() { 
window.setTimeout( "doClock()", 1000 ); 
today = new Date(); 
self.status = today.toString(); 
}
doClock()
//]]>
</script>
<div class="c1" id="logo"><img src="weblogo.png" title="Web Designs By Liz Logo" alt="Web Designs By Liz Logo" /></div>
<table align="center" border="0" cellpadding="0" cellspacing="0">
<tr>
<td><a href="index.html" target="_top" onclick="MM_nbGroup('down','group1','home','home_selected.png',1)" onmouseover="MM_nbGroup('over','home','home_hover.png','home_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="home.png" alt="Home Page" name="home" border="0" id="home" /></a></td>
<td><a href="resume.html" target="_top" onclick="MM_nbGroup('down','group1','resume','resume_selected.png',1)" onmouseover="MM_nbGroup('over','resume','resume_hover.png','resume_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="resume.png" alt="Resume" name="resume" border="0" id="resume" /></a></td>
<td><a href="contact.html" target="_top" onclick="MM_nbGroup('down','group1','contact','contact_selected.png',1)" onmouseover="MM_nbGroup('over','contact','contact_hover.png','contact_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="contact.png" alt="Contact Page" name="contact" border="0" id="contact" /></a></td>
<td><a href="portfolio.php" target="_top" onclick="MM_nbGroup('down','group1','portfolio','portfolio_selected.png',1)" onmouseover="MM_nbGroup('over','portfolio','portfolio_hover.png','portfolio_selected.png',1)" onmouseout="MM_nbGroup('out')"><img name="portfolio" src="portfolio.png" border="0" alt="Portfolio" /></a></td>
<td><a href="testimonials.php" target="_top" onclick="MM_nbGroup('down','group1','testimonials','testimonials_selected.png',1)" onmouseover="MM_nbGroup('over','testimonials','testimonials_hover.png','testimonials_selected.png',1)" onmouseout="MM_nbGroup('out')"><img name="testimonials" src="testimonials_selected.png" border="0" alt="Testimonials" /></a></td>
</tr>
</table>
<div id="resume_title" class="body"><div class="c1"></div>
<table width="900" align="center">
<tr>
<td class="style2" align="center">
<h1>Give Your Testimonial</h1>
</td>
</tr>
<tr>
<td class="style2">
<table class="style2" align="center">
<tr>
<td>


<form name="comment" id="comment" onsubmit="return validateFormOnSubmit(this)" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0" cellspacing="0" cellpadding="5" width="662" class="style2">
<tr>
<td align="left"><label for="name"> Name:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner" id="comment_owner" size="30" value="<?php echo $name; ?>"/></div>
</td>
</tr>
<tr>
<td align="left"><label for="email">E-mail:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner_email" id="comment_owner_email" size="30" value="<?php echo $email; ?>"/></div>
</td>
</tr>
<tr>
<td align="left"><label for="url">URL:</label></td>
<td>
<div class="c2"><input type="text" name="url" id="url" size="30" value="<?php echo $url; ?>"/></div>
</td>
</tr>
<tr>
<td align="left">
<label for="comment">Comments:</label>
</td>
<td>
<textarea name="comment" id="comment" rows="5" cols="30" value="<?php echo $comment; ?>">
</textarea></td>
</tr>
<tr>
<td colspan="4">
<div class="c1"><input name="submit" type="submit" value="Submit" /> <input type="reset" name="reset" id="reset" value="Reset" /></div>
</td>
<td width="2"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div id="footer" class="style2 c1"><br />
<em>Adobe Photoshop, Illustrator, InDesign, Dreamweaver, and Flash logos<br />
are trademarks of Adobe Systems Incorporated.<br />
<br />
Copyright © 2009 Liz Kula. All rights reserved.</em>
<div id="foot-nav">
<ul>
<li><a href="http://validator.w3.org/check?uri=http://webdesignsbyliz.com/resume.html" target="_blank"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a></li>
<li><a href="http://jigsaw.w3.org/css-validator/validator?uri=http://webdesignsbyliz.com/global.css" target="_blank"><img class="c2" src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS!" /></a></li>
</ul>
</div>
</div>
</body>
</html>

 

Thanks guys!

Link to comment
Share on other sites

ok twilitegxa, I think you did good following the instructions I gave you since its working, let me clean up your code and give it to you "ready for upload".

 

I have told you that you MUST NOT print any thing before you use the function header, you didn't really echo or print on purpose but any html code before the function header considered as "printing" or sending information to the browser of how to deal with the page, basically you can't tell the browser to open html tag and carry on then after few lines in a certain condition you change your mind and you want it to go to different page.

 

What this means that you have to put your php code that has the header function ABOVE the html tag, otherwise the html will send headers to the browser and you can't send headers twice in one page.

 

The code after modification should be like this:

 

 <?php



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

//connect to server and select database
$conn = mysql_connect("localhost", "webdes17_twilite", "minimoon")
    or die(mysql_error());
$db = mysql_select_db("webdes17_testimonials", $conn) or die(mysql_error());

//create and issue the first query
$name=mysql_real_escape_string($_POST['comment_owner']);
$email=mysql_real_escape_string($_POST['comment_owner_email']); 
$url=mysql_real_escape_string($_POST['url']);
$comment=mysql_real_escape_string($_POST['comment']);

$error='';//initialize $error to blank
//wrap all errors in one if statement
if(!$$name || !$url || !$email || !$comment) {
if(trim($name)=='' ){
      $error.="Please enter your name!<br />"; //concatenate the $error Message with a line break
  }
  if(trim($url)==''){
      $error.="Please enter your web address!<br />";//concatenate more to $error  
  }
  else {
        if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url)) {
        $error.="The URL you entered was not valid!<br />";
        
        }
    }
  if(trim($email)==''){
    $error.="Plese enter your e-mail address!<br />";
  }
      else {
        if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) {
        $error.="The e-mail you entered was not valid!<br />";
        
        }
    }
    if(trim($comment)=='' ){
      $error.="Please enter your comment!<br />"; //concatenate the $error Message with a line break
  }	
  
  //either this line will be executed or the header function line, not both!
  echo "<div class=error><span style=color:red>$error</span><br /></div>";
  
} else {
  //inserting the data should be before directing
  $sql="INSERT INTO user_comments (comment_id, comment, comment_create_time, comment_owner, comment_owner_email, url) VALUES ('', '$comment', now(), '$name','$email', '$url')"; 

mysql_query($sql,$conn) or die(mysql_error());

header( 'Location: testimonials.php' ) ;
}
  
   
} else {

$name= '';
$email= '';
$url= '';
$comment= '';
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Web Designs By Liz - Testimonials</title>

<style type="text/css" media="screen">
/*<![CDATA[*/
@import url(global.css);
/*]]>*/
</style>

<script type="text/javascript">
//<![CDATA[
<!--
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_nbGroup(event, grpName) { //v6.0
  var i,img,nbArr,args=MM_nbGroup.arguments;
  if (event == "init" && args.length > 2) {
    if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
      img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
      if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
      nbArr[nbArr.length] = img;
      for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
        if (!img.MM_up) img.MM_up = img.src;
        img.src = img.MM_dn = args[i+1];
        nbArr[nbArr.length] = img;
    } }
  } else if (event == "over") {
    document.MM_nbOver = nbArr = new Array();
    for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = (img.MM_dn && args[i+2]) ? args[i+2] : ((args[i+1])? args[i+1] : img.MM_up);
      nbArr[nbArr.length] = img;
    }
  } else if (event == "out" ) {
    for (i=0; i < document.MM_nbOver.length; i++) {
      img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
  } else if (event == "down") {
    nbArr = document[grpName];
    if (nbArr)
      for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
    document[grpName] = nbArr = new Array();
    for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = img.MM_dn = (args[i+1])? args[i+1] : img.MM_up;
      nbArr[nbArr.length] = img;
  } }
}
//-->
//]]>
</script>
<script type="text/javascript" language="JavaScript">
//<![CDATA[
<!--
function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}
//-->
//]]>
</script>
<!-- Validation Script -->
<script type="text/javascript">
function validateFormOnSubmit(theForm) {
var reason = "";

  reason += validateUsername(theForm.comment_owner);
  reason += validateEmail(theForm.comment_owner_email);
  reason += validatePhone(theForm.url);
  reason += validateEmpty(theForm.comment);
     
  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }

}

function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores

    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "Please enter your name.\n";
    }
    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 = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "Please enter your e-mail address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid e-mail address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "Your e-mail address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}
function validatePhone(fld) {
      var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
var urlfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var urlFilter = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;

    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "Please enter your web address.\n";
    } else if (!urlFilter.test(urlfld)) {              //test url for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid web address.\n";
    }
    return error;
}
function validateEmpty(fld) {
    var error = "";

    if (fld.value.length == 0) {
        fld.style.background = 'Yellow';
        error = "Please enter your comment.\n"
    } else {
        fld.style.background = 'White';
    }
    return error; 
}
</script>
<!--End Validation Script -->
</head>
<body onload="MM_preloadImages('home_selected.png','home_hover.png','resume.png','resume_hover.png','resume_selected.png','contact_selected.png','contact_hover.png','portfolio_selected.png','portfolio_hover.png')">
<script language="JavaScript" type="text/javascript">
//<![CDATA[

function doClock() {
window.setTimeout( "doClock()", 1000 );
today = new Date();
self.status = today.toString();
}
doClock()
//]]>
</script>
<div class="c1" id="logo"><img src="weblogo.png" title="Web Designs By Liz Logo" alt="Web Designs By Liz Logo" /></div>
<table align="center" border="0" cellpadding="0" cellspacing="0">
<tr>
<td><a href="index.html" target="_top" onclick="MM_nbGroup('down','group1','home','home_selected.png',1)" onmouseover="MM_nbGroup('over','home','home_hover.png','home_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="home.png" alt="Home Page" name="home" border="0" id="home" /></a></td>
<td><a href="resume.html" target="_top" onclick="MM_nbGroup('down','group1','resume','resume_selected.png',1)" onmouseover="MM_nbGroup('over','resume','resume_hover.png','resume_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="resume.png" alt="Resume" name="resume" border="0" id="resume" /></a></td>
<td><a href="contact.html" target="_top" onclick="MM_nbGroup('down','group1','contact','contact_selected.png',1)" onmouseover="MM_nbGroup('over','contact','contact_hover.png','contact_selected.png',1)" onmouseout="MM_nbGroup('out')"><img src="contact.png" alt="Contact Page" name="contact" border="0" id="contact" /></a></td>
<td><a href="portfolio.php" target="_top" onclick="MM_nbGroup('down','group1','portfolio','portfolio_selected.png',1)" onmouseover="MM_nbGroup('over','portfolio','portfolio_hover.png','portfolio_selected.png',1)" onmouseout="MM_nbGroup('out')"><img name="portfolio" src="portfolio.png" border="0" alt="Portfolio" /></a></td>
<td><a href="testimonials.php" target="_top" onclick="MM_nbGroup('down','group1','testimonials','testimonials_selected.png',1)" onmouseover="MM_nbGroup('over','testimonials','testimonials_hover.png','testimonials_selected.png',1)" onmouseout="MM_nbGroup('out')"><img name="testimonials" src="testimonials_selected.png" border="0" alt="Testimonials" /></a></td>
</tr>
</table>
<div id="resume_title" class="body"><div class="c1"></div>
<table width="900" align="center">
<tr>
<td class="style2" align="center">
<h1>Give Your Testimonial</h1>
</td>
</tr>
<tr>
<td class="style2">
<table class="style2" align="center">
<tr>
<td>


<form name="comment" id="comment" onsubmit="return validateFormOnSubmit(this)" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0" cellspacing="0" cellpadding="5" width="662" class="style2">
<tr>
<td align="left"><label for="name"> Name:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner" id="comment_owner" size="30" value="<?php echo $name; ?>"/></div>
</td>
</tr>
<tr>
<td align="left"><label for="email">E-mail:</label></td>
<td>
<div class="c2"><input type="text" name="comment_owner_email" id="comment_owner_email" size="30" value="<?php echo $email; ?>"/></div>
</td>
</tr>
<tr>
<td align="left"><label for="url">URL:</label></td>
<td>
<div class="c2"><input type="text" name="url" id="url" size="30" value="<?php echo $url; ?>"/></div>
</td>
</tr>
<tr>
<td align="left">
<label for="comment">Comments:</label>
</td>
<td>
<textarea name="comment" id="comment" rows="5" cols="30"><?php echo $comment; ?></textarea>
</td>
</tr>
<tr>
<td colspan="4">
<div class="c1"><input name="submit" type="submit" value="Submit" /> <input type="reset" name="reset" id="reset" value="Reset" /></div>
</td>
<td width="2"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div id="footer" class="style2 c1"><br />
<em>Adobe Photoshop, Illustrator, InDesign, Dreamweaver, and Flash logos<br />
are trademarks of Adobe Systems Incorporated.<br />
<br />
Copyright © 2009 Liz Kula. All rights reserved.</em>
<div id="foot-nav">
<ul>
<li><a href="http://validator.w3.org/check?uri=http://webdesignsbyliz.com/resume.html" target="_blank"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a></li>
<li><a href="http://jigsaw.w3.org/css-validator/validator?uri=http://webdesignsbyliz.com/global.css" target="_blank"><img class="c2" src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS!" /></a></li>
</ul>
</div>
</div>
</body>
</html>

 

I believe this code is working and ready for uploading, I altered it a little bit to make it cleaner and wrapped up some if statements and deleted some of them.

 

see these are some tips for you:

 

Don't connect to the database unless its necessary (since you have just one page unlike big projects) because connecting to the database is probably the slowest function in php and makes your page slow.

if the user is opening this page for the first time, there is no need for any connection!

 

since you assigned the $_POST values to local variables why still using $_POST values in checking empty strings?, this is just more typing and confusing.

 

this tag <textarea> doesn't have a value attribute, you just put the php in between the opening tag and the closing tag.

 

don't put useless or UN-necessary If statements, they litter your code and add more confusion if its long.

 

don't put any thing you need to happen in the page after you redirect it because its not going to be executed since the browser will go to a different page, I have not tried to that before, but I am pretty sure that it won't work.

 

by the way, I didn't mess with your JavaScript because I am not that good in it but it looks fine to me, I have used such code before and it works.

 

Good Luck!

 

Now I think this thread can be marked as solved LOL.

Link to comment
Share on other sites

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

Join the conversation

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

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

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

×   Your previous content has been restored.   Clear editor

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

×
×
  • Create New...

Important Information

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