Jump to content

error checking


pritam79

Recommended Posts

hi everyone, i am using this form to submit the posts made by users. I have not included any error checking here, like if the user leaves a field blank and submits the form. What i want now is that the form should generate error messages whenever the user leaves a field blank and SUBMITS the form, and the error should be displayed right next to the blank text box. I dont want to use javascript, instead i want to do the error checking in PHP as well. thanks to all.........

Link to comment
Share on other sites

See the forms part of the W3Schools PHP tutorial, the following two pages and the isset() function. You'll want to check if the field is set and if it's anything different from an empty string (i.e. "").

Link to comment
Share on other sites

The basic pattern is this.1. The form AND the script that validates the forms input are in fact in the SAME document. That is, the form submits to itself.2. The validating script is at the top of the document. It has three things to do:3. See if any form data was received at all. If not, output the HTML section with no changes.4. If form data was submitted, validate it. Keep track of the failures. Before outputting the HTML, modify it (or maybe just the CSS) so that errors are in some way highlighted. (An icon is visible, a label prints in red, etc.)5. If the form data is correct, set $_SESSION values and redirect execution to a new document using a location header.

Link to comment
Share on other sites

The basic pattern is this.1. The form AND the script that validates the forms input are in fact in the SAME document. Th..............
i am using this script, but when i click submit, the errors are not detected even when i leave a field empty, and that empty field gets inserted into Mysql table as a blank record. This is the script..<?phpinclude "header1.php";?> <?php // Connect to database if($_SERVER['REQUEST_METHOD'] == 'POST') { if(!(isset($_POST['name']))) $error['name'] = '<center><font color="red">name cannot be left blank</font></center>'; if(!(isset($_POST['title']))) $error['title'] = '<center><font color="red">title cannot be left blank</font></center>'; if(!(isset($_POST['post']))) $error['post'] = '<center><font color="red">post cannot be left blank</font></center>'; if(!isset($error)) { $con=mysql_pconnect("localhost","root",""); mysql_select_db("sitedata",$con); $result= mysql_query("SELECT * from sitetable"); $result = mysql_query("INSERT into sitetable(name, title, post) values('$_POST[name]', '$_POST[title]', '$_POST')"); header('Location: index.php'); } }?><div id="content"><?php if(isset($error)){?><?php foreach($error as $key=>$item) echo "<strong>$item</strong></br>"; ?> <?php }?> <center><form action="add_post_form.php" method="post"><br><br> Name: <input type="text" name="name"<?php if((isset($_POST['name']))) echo " value = \"{$_POST['name']}\""; ?>><br><br> Title: <input type="text" name="title"<?php if(isset($_POST['title'])) echo " value = \"{$_POST['title']}\""; ?>><br><br> Post: <textarea name="post"<?php if(isset($_POST['post'])) echo " value = \"{$_POST['post']}\""; ?>></textarea><br><br> <input type="submit" value="Submit"> </form></center></div>
Link to comment
Share on other sites

Initialize your variables first if you are going pass the over the value in the form and put them outside the first IF statement. After you do this, you can then check if the variable has a length. Then you can just check if the $error array is empty.

$error = array();$name = (isset($_POST['name'])) ? $_POST['name'] : "";// rest of your variablesif (strlen($name) === 0) {$error['name'] = '<center><font color="red">name cannot be left blank</font></center>';}// rest of your IF statementsif (empty($error)) {  // insert}

Link to comment
Share on other sites

Initialize your variables first if you are going pass the over the value in the form and put them outside the first IF statement. After you do this, you can then check if the variable has a length. Then you can just check if the $error array is empty.
thanks, it worked, the errors showed. But there is a problem. If there are no input errors, the very first record gets inserted OK. But on subsequent submissions of errorless inputs only the first input is displayed, whereas it should have displayed all the records. The subsequent inputs don’t get inserted in the database table also. Why is it so?
Link to comment
Share on other sites

I don't understand. Please post the code you have now.
This is add_post_form.php
<?phpinclude "header1.php";?>		<?php			   // Connect to database		   if($_SERVER['REQUEST_METHOD'] == 'POST') 			{				   $error = array();				   $name = (isset($_POST['name'])) ? $_POST['name'] : "";				   $title = (isset($_POST['title'])) ? $_POST['title'] : "";				   $post = (isset($_POST['post'])) ? $_POST['post'] : "";				   				   if(strlen($name) === 0)					{					 $error['name'] = '<center><font color="red">name cannot be left blank</font></center>';					}				   if(strlen($title) === 0)					{					 $error['title'] = '<center><font color="red">title cannot be left blank</font></center>';					}				   if(strlen($post) === 0)					{					 $error['post'] = '<center><font color="red">post cannot be left blank</font></center>';					}				  				  if(empty($error)) 					 {					  $con=mysql_pconnect("localhost","root","");					  mysql_select_db("sitedata",$con);					  $result= mysql_query("SELECT * from sitetable");					  $result = mysql_query("INSERT into sitetable(uid, name, title, post) values('', '$_POST[name]', '$_POST[title]', '$_POST[post]')");					  header('Location: index.php');					 }				   			   }?><div id="content"><?php	if(isset($error)){?><?php foreach($error as $key=>$item) echo "<strong>$item</strong></br>"; ?>    <?php	}?>  <center><form action="add_post_form.php" method="post"><br><br>   Name: <input type="text" name="name"<?php if(isset($_POST['name'])) echo " value = \"{$_POST['name']}\""; ?>><br><br>   Title: <input type="text" name="title"<?php if(isset($_POST['title'])) echo " value = \"{$_POST['title']}\""; ?>><br><br>   Post: <textarea name="post"<?php if(isset($_POST['post'])) echo " value = \"{$_POST['post']}\""; ?>></textarea><br><br>   <input type="submit" value="Submit">  </form></center></div>

And this is index.php

<?phpinclude "header1.php";?><div id="content"><table bordercolor="white"> <?php	 $con=mysql_pconnect("localhost","root","");	 mysql_select_db("sitedata",$con);	 $result= mysql_query("SELECT * from sitetable order by uid");	 while($row = mysql_fetch_array($result)) 	 {	   $name = $row['name'];	   $title = $row['title'];	   $post = $row['post'];	   	   echo "<tr><td width=\"190px\" height=\"128px\"><br>Posted by: $name ";	   echo "<br>Title: $title </td>";	   echo "<td height=\"128px\">$post</td></tr>";	 }?></table></div>

Link to comment
Share on other sites

So you're saying that the first insert goes in fine, but if you try it again, it doesn't insert another. I'm not sure what could be causing this. I suggest you debug your code. The following code should be put at the top of your script. It will tell you everything that may be wrong with it.

  error_reporting(E_ALL);  ini_set('display_errors', 1);

Also, put your initialized variables outside the first IF statement.

  $name = (isset($_POST['name'])) ? $_POST['name'] : "";  $title = (isset($_POST['title'])) ? $_POST['title'] : "";  $post = (isset($_POST['post'])) ? $_POST['post'] : "";  if (condition) {	// whatever  }

After you do this, you can replace the code on your form with this one:

<input type="text" name="name" value="<?php echo $name; ?>"><br><br>

Instead of:

$result = mysql_query("INSERT into sitetable(uid, name, title, post) values('', '$_POST[name]', '$_POST[title]', '$_POST[post]')");

Try:

$result = mysql_query("INSERT into sitetable(uid, name, title, post) values('', '$name', '$title', '$post')");

Link to comment
Share on other sites

So you're saying that the first insert goes in fine, but if you try it again, it doesn't insert another. I'm not sure what could be causing this. I suggest you debug your code. The following code should be put at the top of your script. It will tell you everything that may be wrong with it.
  error_reporting(E_ALL);Sorry, but nothing seems to be working. I have tried out everything but the result is the same. These are the messages that i get and these get displayed inside the title and name text boxes respectively.<br /> <b>Notice</b>:  Undefined variable: title in <b>C:\wamp\www\Site\add_post_form.php</b> on line <b>54</b><br /><br /> <b>Notice</b>:  Undefined variable: name in <b>C:\wamp\www\Site\add_post_form.php</b> on line <b>55</b><br />
Link to comment
Share on other sites

You are getting those errors because you have the initialized variables only when you press the button. You should initialize them regardless.

  $error = array();  $name = (isset($_POST['name'])) ? $_POST['name'] : "";  $title = (isset($_POST['title'])) ? $_POST['title'] : "";  $post = (isset($_POST['post'])) ? $_POST['post'] : "";  if($_SERVER['REQUEST_METHOD'] == 'POST')  {	// rest of your code  }

When you are submitting queries to the database it's best to echo out any mysql errors to get exactly what's going wrong.

  $result = mysql_query("INSERT into sitetable(uid, name, title, post) values('', '$name', '$title', '$post')");  if (!$result) {echo mysql_error();}

Link to comment
Share on other sites

im doing a code same as yours.. my only problem is to put it NEXT to the field where the error is..visit this post this should help you:http://w3schools.invisionzone.com/index.php?showtopic=12509POST #6....

i am using this script, but when i click submit, the errors are not detected even when i leave a field empty, and that empty field gets inserted into Mysql table as a blank record. This is the script..<?phpinclude "header1.php";?> <?php // Connect to database if($_SERVER['REQUEST_METHOD'] == 'POST') { if(!(isset($_POST['name']))) $error['name'] = '<center><font color="red">name cannot be left blank</font></center>'; if(!(isset($_POST['title']))) $error['title'] = '<center><font color="red">title cannot be left blank</font></center>'; if(!(isset($_POST['post']))) $error['post'] = '<center><font color="red">post cannot be left blank</font></center>'; if(!isset($error)) { $con=mysql_pconnect("localhost","root",""); mysql_select_db("sitedata",$con); $result= mysql_query("SELECT * from sitetable"); $result = mysql_query("INSERT into sitetable(name, title, post) values('$_POST[name]', '$_POST[title]', '$_POST')"); header('Location: index.php'); } }?><div id="content"><?php if(isset($error)){?><?php foreach($error as $key=>$item) echo "<strong>$item</strong></br>"; ?> <?php }?> <center><form action="add_post_form.php" method="post"><br><br> Name: <input type="text" name="name"<?php if((isset($_POST['name']))) echo " value = \"{$_POST['name']}\""; ?>><br><br> Title: <input type="text" name="title"<?php if(isset($_POST['title'])) echo " value = \"{$_POST['title']}\""; ?>><br><br> Post: <textarea name="post"<?php if(isset($_POST['post'])) echo " value = \"{$_POST['post']}\""; ?>></textarea><br><br> <input type="submit" value="Submit"> </form></center></div>
Link to comment
Share on other sites

  $result = mysql_query("INSERT into sitetable(uid, name, title, post) values('', '$name', '$title', '$post')");  if (!$result) {echo mysql_error();}

When i use if(!$result) {echo mysql_error(); ,I get this error message- Duplicate entry '0' for key 'PRIMARY'
Link to comment
Share on other sites

got the script working ok. i m displaying the error messages on top of the form. but how do i display them next to the form fields?
You assign the error message into a string.
if (!$result) {$err .= mysql_error();}

Later down in your code, just echo out $err wherever you want.

Link to comment
Share on other sites

I have a user registration script in PHP that works OK and inserts the user information into the MySql table. The fields are "uid, username, password and email". uid is the primary key of type integer, username and password are varchar. the problem is that after registering a user all the user details get into the MySq table except the 'password' field. which remains blank in the MySql table. why is it so? plz help.

Link to comment
Share on other sites

Please post your code.
This is the script that registers a user successfully and inserts everything into the database except the ‘password’.
<?phpsession_start();// If form data is posted, run processing scriptif ($_SERVER['REQUEST_METHOD'] == 'POST')   {	 require("posting_fns.php");		if (!(isset($_POST['email']) && valid_email($_POST['email']))) $error['email'] = '<center><font color="red">Not a valid email address</font></center>';   	if(!isset($_POST['username']) || (strlen($_POST['username']) < 6 ) || (strlen($_POST['username']) > 16)) $error['username'] = '<center><font color="red">Username must be between 6 to 16 characters<font></center>';  		if($_POST['username'] == $_POST['password1']) $error['username'] = '<center><font color="red">Username and Password cannot be same</font></center>';  	 if(isset($_POST['password1']) && isset($_POST['password2'])) 	  {		if($_POST['password1'] !== $_POST['password2']) $error['password'] = '<center><font color="red">Passwords do not match</font></center>';				if (strlen($_POST['password1']) < 6 || strlen($_POST['password1']) > 16) $error['password'] = '<center><font color="red">Password must be between 6 to 16 characters</font></center>';  	  }	 else $error['password'] = '<center><font color="red">Password data not found.  Possible form error.</font></center>'; 	 	if(!isset($error))	  {		$conn = db_connect() or die('Unable to connect to the database');		mysql_select_db('sitedata', $conn) or die('Could not select database.');		$username = mysql_escape_string($_POST['username']);				$result = mysql_query("select * from users where username = '$username'");				if($result)		 {			if(mysql_num_rows($result) < 1) 			{				$password = mysql_escape_string($_POST['password']);								$email = mysql_escape_string($_POST['email']);								$result = mysql_query("insert into users values('', '$username', '$password', '$email')");								if($result)				 {					$valid_user = $username;										session_register("valid_user");										header('Location: login.php');										exit();									 } else $error['database'] = '<center><font color="red">An unknown database error has occurred on insert</font></center>';				 			} else $error['username'] = '<center><font color="red">Username already exists.</font></center>';					} else $error['database'] = '<center><font color="red">An unknown database error has occurred on select</font></center>';	}}include "header1.php";?>  <div id="content"><?php	if(isset($error)){?><?php foreach($error as $key=>$item) echo "<strong>$item</strong></br>"; ?>    <?php	}?><form action="register.php" name="register_form" method="post"><br><table style="height: 284px; text-align: left" align="center">	<tr>		<td style="width: 204px; font-weight: 700; font-family: Arial;">E-mail address : </td>		<td style="width: 290px">		<input type="text" size="20" name="email"<?php if(isset($_POST['email'])) echo " value = \"{$_POST['email']}\""; ?> style="width: 145px"></td>	</tr>	<tr>		<td style="width: 204px; height: 47px; font-weight: 700; font-family: Arial;">Preferred username : </td>		<td style="width: 290px; height: 47px;">		<input type="text" size="20" name="username"<?php if(isset($_POST['username'])) echo " value = \"{$_POST['username']}\""; ?> style="width: 145px"> (6 to 16 chars)</td>	</tr>	<tr>		<td style="width: 204px; font-family: Arial; font-weight: 700;">Password : </td>		<td style="width: 290px">		<input type="password" size="20" name="password1"<?php if(isset($_POST['password1'])) echo " value = \"{$_POST['password1']}\""; ?> style="width: 145px"> (6 to 16 chars)</td>	</tr>	<tr>		<td style="width: 204px; height: 56px; font-family: Arial; font-weight: 700;">Confirm password : </td>		<td style="width: 290px; height: 56px;">		<input type="password" size="20" name="password2"<?php if(isset($_POST['password2'])) echo " value = \"{$_POST['password2']}\""; ?> style="width: 145px"></td>	</tr>	<tr>		<td style="width: 204px"> </td>		<td style="width: 290px"><input type="submit"  name="Submit" value="register">   <input type="reset" name="Reset" value="reset"></td>	</tr></table></form></div></body></html>

Link to comment
Share on other sites

if (strlen($_POST['password1']) < 6 && strlen($_POST['password1']) > 16)

This above line should not have an OR operator. You wanted AND.

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

You are sure you don't mean "password1" or "password2"?

Link to comment
Share on other sites

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

You are sure you don't mean "password1" or "password2"?

Thanks, the registration script is working now and a user is directed to the login.php page. But now when I try logging in, I get this error message: Deprecated: Function session_register() is deprecated in C:\wamp\www\Site\login.php on line 13This is login.php
<?phpsession_start();if ($_SERVER['REQUEST_METHOD'] == 'POST') {	require("posting_fns.php");	  if(!filled_out($_POST)) $error['form'] = '<center><font color="red">You have not filled the form completely</font></center>';	  if($_POST['username'] && $_POST['password'])  // they have just tried logging in		{		  if(login($_POST['username'], $_POST['password'])) 			{			  // if they are in the database, register the user id			   $valid_user = $_POST['username'];			   session_register("valid_user");			}		  else				   // unsuccessful login			$error['form'] = '<center><font color="red">You could not be logged in.<br>Check your username and/or password</font></center>';			 		}	   if(check_valid_user())		 {		  header('Location: index.php'); 		 }  }include "header1.php";?>  <div id="content"><?php	if(isset($error)){?><?php foreach($error as $key=>$item) echo "<strong>$item</strong></br>"; ?>    <?php	}?><html><body><table style="width: 768px; height: 195px;"><form action="login.php" method="post">	<tr>		<td colspan="2" style="text-align: center; font-weight: 700; font-family: Arial;">Login to start</td>	</tr>	<tr>		<td style="text-align: right; width: 341px; font-family: Arial;">Username : </td>		<td style="text-align: left"><input type="text" size="20" name="username"<?php if(isset($_POST['username'])) echo " value = \"{$_POST['username']}\""; ?>></td>	</tr>	<tr>		<td style="text-align: right; width: 341px; font-family: Arial;">Password : </td>		<td style="text-align: left"><input type="password" size="20" name="password"> <a href="forgot_form.php">forgot 		password ?</a>   <a href="register.php">not registered ?</a></td>	</tr>	<tr>		<td colspan="2" style="text-align: center"><input type="submit" name="submit" value="Submit">	<input type="reset" name="reset" value="Reset">	</td>	</tr></form></table></body></html></div>

Link to comment
Share on other sites

session_register() is deprecated (as the error says) - just assign to the $_SESSION array.

Link to comment
Share on other sites

Hi there, I used $_SESSION["valid_user"] in place of session_register. But after ‘logging in’ the user is not directed to the index page. I think the below function that is in another page is returning 0. This is the function.

function check_valid_user()	{	// see if somebody is logged in and notify them if not	 global $valid_user;	 if(isset($_SESSION['$valid_user']))					return 1;	 return 0;	}

Link to comment
Share on other sites

Your mixing up the string, "valid_user", and the variable, $valid_user.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...