Jump to content

trying to echo out string variables in a form


webguync

Recommended Posts

I need to echo out some string variables in a form. I also want to add some validation for Name, email etc. I think I have the code right or close, but I can an error on the index.php page which is.

"Fatal error:  Call to undefined function  form_row_class() in index.php on line 14"

 

here is the code for the form


<!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>
    <title>String Tester</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>
</head>

<body>
    <div id="content">
        <h1>String Tester</h1>
        <form action="submit.php" method="post">
  <table>
    <tr class="<?php echo form_row_class("name") ?>" >
      <th><label for="first_name">Name</label></th>
      <td>
        <input name="first_name" id="first_name" type="text" value="<?php echo h($_POST['name']); ?>" />
        <?php echo error_for('name') ?>
      </td>
    </tr>
    
    <tr class="<?php echo form_row_class("email") ?>">
      <th><label for="email">Email Address</label></th>
      <td>
        <input name="email" id="email" type="text" value="<?php echo h($_POST['email']); ?>" />
        <?php echo error_for('email') ?>
      </td>
    </tr>
   
    <tr>
      <th></th>
      <td><input type="submit" value="submit" /></td>
    </tr>
  </table>
</form>

        <h2>Message:</h2>
        <?php 
	echo "<table>";
	echo "<tr><td>";
	echo $name;
	echo "</td></tr>";
	echo "<tr><td>";
	echo $email;
	echo "</td></tr>";
	echo "<tr><td>";
	echo $phone;
	echo "</td></tr>";
	echo "</table>";
	?>

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

 

and the submit portion

<?php

// If request is a form submission
if($_SERVER['REQUEST_METHOD'] == 'POST'){
  // Validation

  // Check first_name is non-blank
  if(0 === preg_match("/\S+/", $_POST['name'])){
    $errors['name'] = "Please enter a name.";
  }
  
  // Check email is valid (enough)
  if(0 === preg_match("/.+@.+\..+/", $_POST['email'])){
    $errors['email'] = "Please enter a valid email address.";
  }
  
  // validate a phone number
if( !preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone) ) {
echo 'Please enter a valid phone number';
}


// If no validation errors
  if(0 === count($errors)){
    
    // Sanitize first, last, and email
    $name = mysql_real_escape_string($_POST['name']);
    $email= mysql_real_escape_string($_POST['email']);
    $email= mysql_real_escape_string($_POST['phone']);
  }

// Helpers
function form_row_class($name){
  global $errors;
  return $errors[$name] ? "form_error_row" : "";
}

function error_for($name){
  global $errors;
  if($errors[$name]){
    return "<div class='form_error'>" . $errors[$name] . "</div>";
  }


function h($string){
  return htmlspecialchars($string);
}

?>

 

 

 

probably something simple I am missing.

Link to comment
Share on other sites

function form_row_class($name){
  global $errors;
  return $errors[$name] ? "form_error_row" : "";
}

 

must also be declared in your form page. perhaps have the helper functions in a separate file, and include them into the form and submit pages .

Link to comment
Share on other sites

I put the functions in an include but now I am getting the following error.

 

"Parse error: syntax error, unexpected $end in functions.php on line 18".

 

the code to include the functions is:

<?php
ini_set('display_errors',1);
error_reporting(-1);
require('functions.php');
?>
<!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>
    <title>String Tester</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>
</head>

<body>
    <div id="content">
        <h1>String Tester</h1>
        <form action="submit.php" method="post">
  <table>
    <tr class="<?php echo form_row_class("name") ?>" >
      <th><label for="first_name">Name</label></th>
      <td>
        <input name="first_name" id="first_name" type="text" value="<?php echo h($_POST['name']); ?>" />
        <?php echo error_for('name') ?>
      </td>
    </tr>
    
    <tr class="<?php echo form_row_class("email") ?>">
      <th><label for="email">Email Address</label></th>
      <td>
        <input name="email" id="email" type="text" value="<?php echo h($_POST['email']); ?>" />
        <?php echo error_for('email') ?>
      </td>
    </tr>
   
    <tr>
      <th></th>
      <td><input type="submit" value="submit" /></td>
    </tr>
  </table>
</form>

        <h2>Message:</h2>
        <?php 
	echo "<table>";
	echo "<tr><td>";
	echo $name;
	echo "</td></tr>";
	echo "<tr><td>";
	echo $email;
	echo "</td></tr>";
	echo "<tr><td>";
	echo $phone;
	echo "</td></tr>";
	echo "</table>";
	?>

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

 

and functions.php is:

 

<?php
// Functions
function form_row_class($name){
  global $errors;
  return $errors[$name] ? "form_error_row" : "";
}

function error_for($name){
  global $errors;
  if($errors[$name]){
    return "<div class='form_error'>" . $errors[$name] . "</div>";
  }


function h($string){
  return htmlspecialchars($string);
}
?>

Link to comment
Share on other sites

would this be right now?

 


<?php
// Functions
function form_row_class($name){
  global $errors;
  return $errors[$name] ? "form_error_row" : "";
}

function error_for($name){
  global $errors;
}
  if($errors[$name]){
    return "<div class='form_error'>" . $errors[$name] . "</div>";
  }


function h($string){
  return htmlspecialchars($string);
}
?>

 

also when I click submit I get an error

 

Parse error: syntax error, unexpected $end in /nfs/c08/h01/mnt/118256/domains/inspired-evolution.com/html/Testing/Strings/ch09_ex1/submit.php on line 40

 

here is the code for submit.php

 


<?php
// If request is a form submission
if($_SERVER['REQUEST_METHOD'] == 'POST'){
  // Validation

  // Check first_name is non-blank
  if(0 === preg_match("/\S+/", $_POST['name'])){
    $errors['name'] = "Please enter a name.";
  }
  
  // Check email is valid (enough)
  if(0 === preg_match("/.+@.+\..+/", $_POST['email'])){
    $errors['email'] = "Please enter a valid email address.";
  }
  
  // validate a phone number
if( !preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone) ) {
echo 'Please enter a valid phone number';
}


// If no validation errors
  if(0 === count($errors)){
    
    // Sanitize first, last, and email
    $name = mysql_real_escape_string($_POST['name']);
    $email= mysql_real_escape_string($_POST['email']);
    $email= mysql_real_escape_string($_POST['phone']);

require('functions.php');
?>

Link to comment
Share on other sites

ok, thx. I fixed that part. The form isn't displaying the submit results though. It echoes an invalid phone number when I enter it as 123-123-1234 format.

 

here is my updated code:

 

index.php

 

<?php

require('functions.php');
?>
<!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>
    <title>String Tester</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>
</head>

<body>
    <div id="content">
        <h1>String Tester</h1>
        <form action="submit.php" method="post">
  <table>
    <tr class="<?php echo form_row_class("name") ?>" >
      <th><label for="name">Name:</label></th>
      <td>
        <input name="name" id="name" type="text" value="<?php echo h($_POST['name']); ?>" />
        <?php echo error_for('name') ?>
      </td>
    </tr>
    
    <tr class="<?php echo form_row_class("email") ?>">
      <th><label for="email">Email Address:</label></th>
      <td>
        <input name="email" id="email" type="text" value="<?php echo h($_POST['email']); ?>" />
        <?php echo error_for('email') ?>
      </td>
    </tr>
      <tr class="<?php echo form_row_class("phone") ?>">
      <th><label for="phone">Phone:</label></th>
      <td>
        <input name="phone" id="phone" type="text" value="<?php echo h($_POST['phone']); ?>" />
        <?php echo error_for('phone') ?>
      </td>
    </tr>
    <tr>
      <th></th>
      <td><input type="submit" value="submit" /></td>
    </tr>
  </table>
</form>

        <h2>Message:</h2>
        <?php 
	echo "<table>";
	echo "<tr><td>";
	echo $name;
	echo "</td></tr>";
	echo "<tr><td>";
	echo $email;
	echo "</td></tr>";
	echo "<tr><td>";
	echo $phone;
	echo "</td></tr>";
	echo "</table>";
	?>

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

 

 

submit.php

 

<?php

// If request is a form submission
if($_SERVER['REQUEST_METHOD'] == 'POST'){
  // Validation

  // Check first_name is non-blank
  if(0 === preg_match("/\S+/", $_POST['name'])){
    $errors['name'] = "Please enter a name.";
  }
  
  // Check email is valid (enough)
  if(0 === preg_match("/.+@.+\..+/", $_POST['email'])){
    $errors['email'] = "Please enter a valid email address.";
  }
  
  // validate a phone number
if( !preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone) ) {
echo 'Please enter a valid phone number';
}


// If no validation errors
  if(0 === count($errors)){
    
    // Sanitize first, last, and email
    $name = ($_POST['name']);
    $email= ($_POST['email']);
    $phone= ($_POST['phone']);
  }
}

require('functions.php');
?>

 

functions.php

 

<?php
// Functions
function form_row_class($name){
  global $errors;
  return $errors[$name] ? "form_error_row" : "";
}

function error_for($name){
  global $errors;
}
  if($errors[$name]){
    return "<div class='form_error'>" . $errors[$name] . "</div>";
  }


function h($string){
  return htmlspecialchars($string);
}
?>

Link to comment
Share on other sites

here is an update. I consolidated my code and it works to an extent. The variable result are echoes on the page. However, the message invalid phone number is displayed no matter what and the error messages for name and email don't display, however the input field is highlighted in red as intended.

 

<?php
// If request is a form submission
if($_SERVER['REQUEST_METHOD'] == 'POST'){
  // Validation

  // Check first_name is non-blank
  if(0 === preg_match("/\S+/", $_POST['name'])){
    $errors['name'] = "Please enter a name.";
  }
  
  // Check email is valid (enough)
  if(0 === preg_match("/.+@.+\..+/", $_POST['email'])){
    $errors['email'] = "Please enter a valid email address.";
  }
  
  // validate a phone number
if( !preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone) ) {
echo 'Please enter a valid phone number';
}


// If no validation errors
  if(0 === count($errors)){
    
    // Sanitize first, last, and email
    $name = ($_POST['name']);
    $email= ($_POST['email']);
    $phone= ($_POST['phone']);
  }
}

require('functions.php');
?>

<!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>
    <title>String Tester</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>
</head>

<body>
    <div id="content">
        <h1>String Tester</h1>
        <form action="index.php" method="post">
  <table>
    <tr class="<?php echo form_row_class("name") ?>" >
      <th><label for="name">Name:</label></th>
      <td>
        <input name="name" id="name" type="text" value="<?php echo h($_POST['name']); ?>" />
        <?php echo error_for('name') ?>
      </td>
    </tr>
    
    <tr class="<?php echo form_row_class("email") ?>">
      <th><label for="email">Email Address:</label></th>
      <td>
        <input name="email" id="email" type="text" value="<?php echo h($_POST['email']); ?>" />
        <?php echo error_for('email') ?>
      </td>
    </tr>
      <tr class="<?php echo form_row_class("phone") ?>">
      <th><label for="phone">Phone:</label></th>
      <td>
        <input name="phone" id="phone" type="text" value="<?php echo h($_POST['phone']); ?>" />
        <?php echo error_for('phone') ?>
      </td>
    </tr>
    <tr>
      <th></th>
      <td><input type="submit" value="submit" /></td>
    </tr>
  </table>
</form>

        <h2>Message:</h2>
        <?php 
	echo "<table>";
	echo "<tr><td>";
	echo $name;
	echo "</td></tr>";
	echo "<tr><td>";
	echo $email;
	echo "</td></tr>";
	echo "<tr><td>";
	echo $phone;
	echo "</td></tr>";
	echo "</table>";
	?>

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

 

functions

<?php
// Functions
function form_row_class($name){
  global $errors;
  return $errors[$name] ? "form_error_row" : "";
}

function error_for($name){
  global $errors;
}
  if($errors[$name]){
    return "<div class='form_error'>" . $errors[$name] . "</div>";
  }


function h($string){
  return htmlspecialchars($string);
}
?>

Link to comment
Share on other sites

ok thanks, I fixed that part. Now how can I debug why the error msg isn't displaying below the form field when it is empty or not entered correctly? I should have the check set up for that but the error msg. doesn't display, only the class to highlight the field. Also what is the best way to reset the form? I want it to clear when a refresh is done.

 

thanks!

Link to comment
Share on other sites

If you want the messages to show up beside the form fields you should use JavaScript to verify the results before you allow the form to be submitted. If there are errors, update an empty <span> or something beside the field with the error message.

 

There is a reset input button in HTML

http://webdesign.about.com/od/htmltags/p/input-reset-tag.htm

Link to comment
Share on other sites

I was kind of hoping to just use the php I have set up for that. This is going to be live, so I don't need to do anything fancy.

 

also I added

 

<input type="reset" name="reset" value="reset">

 

but that doesn't reset the form, maybe because it is using PHP post variables?

 

Link to comment
Share on other sites

My mistake on the Reset button. You'll have to use JavaScript to wipe the form

http://www.javascript-coder.com/javascript-form/javascript-reset-form.phtml

 

If you want to use PHP to display the errors, you will have to change your code.

 

You could make your form submit to itself, and if an error is found, re-display the form with the content previously entered and the errors appended.

You could also have the submit page redirect back to the form page with the errors passed via the query string. If you wanted the content previously entered to remain, you'd have to pass that as well.

<?php 

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$err = array();
if( empty($_POST['name']) )
	$err['name'] = 'Name is a required field';
elseif( !preg_match('/^[a-z]++$/i', $_POST['name']) )
	$err['name'] = 'Name can only be letters';

if( empty($_POST['email']) )
	$err['email']  = 'Email is a required field';
elseif( !preg_match('/@/', $_POST['email']) )
	$err['email'] = 'Email must contain @ symbol';

if( empty($err) ) {
	//function_to_process_data();
	//header( 'Location: http://yoursite.com/success.php' );
	echo 'success';
	exit();
}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>form</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
	<label>Name: <input type="text" name="name" value="<?php if(isset($_POST['name'])) echo htmlspecialchars($_POST['name']); ?>"></label>
	<?php if(isset($err['name'])) echo '<span style="color: red;">'.$err['name'].'</span>' ?>
	<br>
	<label>Email: <input type="text" name="email" value="<?php if(isset($_POST['email'])) echo htmlspecialchars($_POST['email']); ?>"></label>
	<?php if(isset($err['email'])) echo '<span style="color: red;">'.$err['email'].'</span>' ?>
	<br>
	<input type="submit"><input type="reset">
</form>
</body>
</html>

Link to comment
Share on other sites

never mind, I wasn't echoing the post data. I would like the form to still display though and the echoed data to just display below the form.

<?php 

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$err = array();
if( empty($_POST['name']) )
	$err['name'] = 'Name is a required field';
elseif( !preg_match('/^[a-z]++$/i', $_POST['name']) )
	$err['name'] = 'Name can only be letters';

if( empty($_POST['email']) )
	$err['email']  = 'Email is a required field';
elseif( !preg_match('/@/', $_POST['email']) )
	$err['email'] = 'Email must contain @ symbol';

if( empty($err) ) {
	//function_to_process_data();
	echo "<h2>Message:</h2>";
        
	echo "<table>";
	echo "<tr><td>";
	echo $_POST['name'];
	echo "</td></tr>";
	echo "<tr><td>";
	echo $_POST['email'];
	echo "</td></tr>";
	echo "<tr><td>";
	echo $_POST['phone'];
	echo "</td></tr>";
	echo "</table>";

	exit();
}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>String Tester</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>
    <script type="text/javascript">
function clearForm(oForm) {
    
  var elements = oForm.elements; 
    
  oForm.reset();

  for(i=0; i<elements.length; i++) {
      
field_type = elements[i].type.toLowerCase();

switch(field_type) {

	case "text": 
	case "password": 
	case "textarea":
        case "hidden":	

		elements[i].value = ""; 
		break;
        
	case "radio":
	case "checkbox":
  			if (elements[i].checked) {
   				elements[i].checked = false; 
		}
		break;

	case "select-one":
	case "select-multi":
            		elements[i].selectedIndex = -1;
		break;

	default: 
		break;
}
    }
}

</script>
</head>
<body onLoad="clearForms()" onUnload="clearForms()">
<div id="content">
        <h1>String Tester</h1>
<form method="post" action="<?php echo $_SERVER['index_test.php']; ?>">
	<label>Name: <input type="text" name="name" value="<?php if(isset($_POST['name'])) echo htmlspecialchars($_POST['name']); ?>"></label>
	<?php if(isset($err['name'])) echo '<span style="color: red;">'.$err['name'].'</span>' ?>
	<br>
	<label>Email: <input type="text" name="email" value="<?php if(isset($_POST['email'])) echo htmlspecialchars($_POST['email']); ?>"></label>
	<?php if(isset($err['email'])) echo '<span style="color: red;">'.$err['email'].'</span>' ?>
	<br>
         <input type="submit" value="submit" /></td>
        <br>
	<input type="button" name="reset_form" value="Reset Form" onClick="this.form.reset();">
</form>
   
        
    </div>
</body>
</html>

Link to comment
Share on other sites

I think this is working pretty much the way I want. The only slight problem is the reset form using JS only works prior to hitting the submit. Once the POST data is submitted. You cannot clear the form. Any suggestions for that.

 

current code:

 

<?php 

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$err = array();
if( empty($_POST['name']) )
	$err['name'] = 'Name is a required field';
elseif( !preg_match('/^[a-z]++$/i', $_POST['name']) )
	$err['name'] = 'Name can only be letters';

if( empty($_POST['email']) )
	$err['email']  = 'Email is a required field';
elseif( !preg_match('/.+@.+\..+/', $_POST['email']) )
	$err['email'] = 'Email must contain @ symbol';

	if( empty($_POST['phone']) )
	$err['phone']  = 'Phone is a required field';
elseif( !preg_match('/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i', $_POST['phone']) )
	$err['phone'] = 'Phone number is not entered in a valid format [123-123-1234]';

}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>String Tester</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>
    <script type="text/javascript">
function clearForm(oForm) {
    
  var elements = oForm.elements; 
    
  oForm.reset();

  for(i=0; i<elements.length; i++) {
      
field_type = elements[i].type.toLowerCase();

switch(field_type) {

	case "text": 
	case "password": 
	case "textarea":
        case "hidden":	

		elements[i].value = ""; 
		break;
        
	case "radio":
	case "checkbox":
  			if (elements[i].checked) {
   				elements[i].checked = false; 
		}
		break;

	case "select-one":
	case "select-multi":
            		elements[i].selectedIndex = -1;
		break;

	default: 
		break;
}
    }
}

</script>
</head>
<body onLoad="clearForms()" onUnload="clearForms()">
<div id="content">
        <h1>String Tester</h1>
<form method="post" action="<?php echo $_SERVER['index_test.php']; ?>">
	<label>Name: <input type="text" name="name" value="<?php if(isset($_POST['name'])) echo htmlspecialchars($_POST['name']); ?>"></label>
	<?php if(isset($err['name'])) echo '<span style="color: red;">'.$err['name'].'</span>' ?>
	<br>
	<label>Email: <input type="text" name="email" value="<?php if(isset($_POST['email'])) echo htmlspecialchars($_POST['email']); ?>"></label>
	<?php if(isset($err['email'])) echo '<span style="color: red;">'.$err['email'].'</span>' ?>
	<br>
        <label>Phone: <input type="text" name="phone" value="<?php if(isset($_POST['phone'])) echo htmlspecialchars($_POST['phone']); ?>"></label>
	<?php if(isset($err['phone'])) echo '<span style="color: red;">'.$err['phone'].'</span>' ?>
        <br>
         <input type="submit" value="submit" />
        <br><br>
	<input type="button" name="reset_form" value="Reset Form" onClick="this.form.reset();">
</form>
    
   <?php
   	if( empty($err) ) {
	//function_to_process_data();
	echo "<h2>Message:</h2>";
        
	echo "<table>";
	echo "<tr><td>";
	echo ucwords($_POST['name']);
	echo "</td></tr>";
	echo "<tr><td>";
	echo $_POST['email'];
	echo "</td></tr>";
	echo "<tr><td>";
	echo $_POST['phone'];
	echo "</td></tr>";
	echo "</table>";

	exit();
}
?>
        
    </div>
</body>
</html>

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.