Hey friends,

I have a page that I've been working on for HOURS and finally almost have it perfect except for TWO things:

1. Every time I load the page it automatically inserts a blank row of data into my MySQL database. (Submitting it after filling out the for works fine.)
-How can I stop it from dong that every time the page loads?

I've been messing with if (!isset($_POST)) but I can't find the right placement.

2. My email at the bottom isn't sending. Can anyone see a better spot to place the mail() script? (This one is less important)

Thank you!

<?php
include("database.php");
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<?php 
			$name=$_POST["name"];
			$email=$_POST["email"];
			$cat=$_POST["cat"];
			$issue=$_POST["issue"];
			$descript=$_POST["descript"];
			$trouble=$_POST["trouble"];
			$device=$_POST["device"];
			$priority=$_POST["priority"];
?>

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
	<link href="./css/submitticket.css" rel="stylesheet" type="text/css">
	<link rel="stylesheet" href="/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />
	<Title>IT Support - Submit Ticket</Title>	
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
	<script type="text/javascript" src="/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
</head>
<body>

<?php 
			
		if(array_key_exists('submit',$_POST)){
		// Fields that are on form
		$expected = array('name', 'email', 'cat', 'issue', 'descript', 'trouble', 'device', 'priority');
		// Set required fields 
		$required = array('name', 'email', 'descript', 'trouble', 'device'); 
		// Initialize array for errors 
		$errors = array(); 
						
		foreach ($_POST as $field => $value){
		// Assign to $temp and trim spaces if not array 
		$temp = is_array($value) ? $value : trim($value);
		// If field is empty and required, tag onto $errors array 
		if (empty($temp) && in_array($field, $required)) { 
		array_push($errors, $field); 
			} 
		}
						
		//If good to go
		if (empty($errors)){?> 
		<div class="green">Thank you.</div> 
		<?php
		unset($errors);
							
			}
		}	
?>
						
	<div class="container">
	
<header>Submit Ticket</header>
	<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
	<div id="info">
				<table>
					<tr>
						<td>
							
						<!---<img class="small_logo" src=""> -->
						
						</td>
					</tr>
					<tr>
						<td>
							<p>Name
						</td>
						<td>
							<?php if (isset($errors) && in_array('name', $errors)){?>
							<div class="red">Please enter name</div>
							<?php } ?> 
							<input type="text" name="name" id="name" class="info" style="text-align: left;">
							</td>
					</tr>
					<tr>
						<td> 
							<p>Email
						</td>
						<td>
							<input type="text" name="email" id="email" class="info">@example.com
						</td>
					</tr>
				</table>
	</div>
			
			<p>Category:  <input type="hidden" name="cat" id="cat" value="User accounts"><b>User accounts</b></p>
			<p>Issue: <input type="hidden" name="issue" id="issue" value="Unable to Login"><b>Unable to login</b></p>
			<p>Details<br /> 
				<textarea name="descript" id="descript"></textarea></p>
			<p>Previous Troubleshooting <span style="font-size: 12px;">(if applicable)</span><br />
				<textarea name="trouble" id="trouble"></textarea></p>
			<p>Device S/N, IP Address, and/or Location <br />
				<b><textarea name="device" name="device" class="small"></textarea></b></p>
				<p style="float:right; color: white; padding-top:10px;">Priority: <select name="priority" class="button">
							<option value="Low">Low</option>
							<option value="High">High</option>
					</select>
					
					<input type="button" value="Cancel" onClick="history.go(-1);return true;"class="button"> <input name="submit" id="submit" type="submit" value="Submit" class="button"></p>
		</form>
		
<?php
		
	$today = date("M d Y"); 
	$sql="INSERT INTO info (Ticket, Dateadded, Name, Email, Issue, Cat, Descript, Trouble, Device, Priority)
	VALUES
	('$_POST[ticket]','$today','$_POST[name]','$_POST[email]','$_POST[issue]','$_POST[cat]','$_POST[descript]','$_POST[trouble]','$_POST[device]','$_POST[priority]')";
				
		if (!mysql_query($sql,$con))
		 {
		die('Error: ' . mysql_error());
		}
		else 
		{
	$query  = "SELECT ticket, dateadded, name, email, issue, descript, cat, device, trouble, priority FROM info ORDER by ticket DESC LIMIT 1";
	$result = mysql_query($query);
				
				
		while($row = mysql_fetch_array($result, MYSQL_ASSOC))
				{
					$to = "{$row['email']}@me.com";
					$subject = "UWS Support - {$row['cat']} - Ticket #{$row['ticket']}";
					$message = "Thank you for submitting a request to get this issue resolved. Your ticket # is {$row['ticket']}. You will be notified by email if we need any more information or when we've fixed this issue.\n\n Issue: {$row['issue']}\n Details: {$row['descript']}\n Device: {$row['device']}\n\n-UWS Support Team\n\n\nIf you did not submit or submitted this Ticket in error please reply to this email so that we may cancel it.";
					$from = "UWS_IT@group.example.com";
					$headers = "From: $from";
					mail($to,$subject,$message,$headers);	
				
				}
		} 
?>
	
		</div>
	</body>
</html>

Recommended Answers

All 13 Replies

Never mind to question #2 it was working all along I was just putting dummy data in the email field when I was testing it instead of my own email address. Duhh..

Try this logic...i hope this may help 4 u

if($submit)

if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['cat']) || empty($_POST['issue']) || empty($_POST['descript']) || empty($_POST['trouble']) || empty($_POST['device']) || empty($_POST['priority']))
{ echo "Please Fill all the requirement field"; }

i have the same problem everytime i refresh my explorer it will save the blank row in my database so i try dis code and it work...

Simply insert the if(isset($_POST)){ before line number 112 and your problem of blank insertion would be solved

Simply insert the if(isset($_POST)){ before line number 112 and your problem of blank insertion would be solved

Thanks for the help. I did as you said and it still is inserting the blank record on refresh or load of the page. Any other suggestions?

<?php
		
	$today = date("M d Y"); 
 if(isset($_POST)){
	$sql="INSERT INTO info (Ticket, Dateadded, Name, Email, Issue, Cat, Descript, Trouble, Device, Priority)
	VALUES
	('$_POST[ticket]','$today','$_POST[name]','$_POST[email]','$_POST[issue]','$_POST[cat]','$_POST[descript]','$_POST[trouble]','$_POST[device]','$_POST[priority]')";
				
		if (!mysql_query($sql,$con))
		 {
		die('Error: ' . mysql_error());
		}
		else 
		{
	$query  = "SELECT ticket, dateadded, name, email, issue, descript, cat, device, trouble, priority FROM info ORDER by ticket DESC LIMIT 1";
	$result = mysql_query($query);
				
				
		while($row = mysql_fetch_array($result, MYSQL_ASSOC))
				{
					$to = "{$row['email']}m";
					$subject = "UWS Support - {$row['cat']} - Ticket #{$row['ticket']}";
					$message = "Thank you for submitting a request to get this issue resolved. Your ticket # is {$row['ticket']}. You will be notified by email if we need any more information or when we've fixed this issue.\n\n Issue: {$row['issue']}\n Details: {$row['descript']}\n Device: {$row['device']}\n\n-UWS Support Team\n\n\nIf you did not submit or submitted this Ticket in error please reply to this email so that we may cancel it.";
					$from = "UWS_IT@group.example.com";
					$headers = "From: $from";
					mail($to,$subject,$message,$headers);	
				
				}
		} 
		}
?>

I think it may have something to do with me doing a similar thing already to check the form for Validation at the top of the page.

if(array_key_exists('submit',$_POST)){

on line 31

Something tells me I'll need to place an if statement or something of the like somewhere. I've tried every combo I can think of. HELP! lol

Try this logic...i hope this may help 4 u

if($submit)

if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['cat']) || empty($_POST['issue']) || empty($_POST['descript']) || empty($_POST['trouble']) || empty($_POST['device']) || empty($_POST['priority']))
{ echo "Please Fill all the requirement field"; }

i have the same problem everytime i refresh my explorer it will save the blank row in my database so i try dis code and it work...

Thank you for the advice. I already have a form field validation that works properly and that is dynamic so that i load errors for each field. So I'd rather not change my validation. Any other suggestions?

you could try making one of the entries a primary key and if needed not null that way it wont be null and duplicate entries wont be written

you could try making one of the entries a primary key and if needed not null that way it wont be null and duplicate entries wont be written

That actually sounds like a good Idea. Do I make the entry a PRIMARY in the MySQL database in PhpAdmin? And could you give me a quick example of how to see if the entry is not null in php?

I would really appreciate it.

Thank you in advance!

Member Avatar for diafol

You shouldn't pass a form's data to itself. This usually causes data to be resubmitted on refresh. This is why form_handler files/pages are set up. Data can be posted to these via ajax or traditional form submit.

You can use session data to keep error messages etc alive for the return journey to the form page.

FORM  ->  HANDLER  --(success)-->  PAGE 6 
 ^            |
 |          (fail)             
 |            |
 |            V
 |---(set session data)

I don't know if that makes sense. It may seem like less work to send a form to itself, but that does open you up to the resubmit problem.

You shouldn't pass a form's data to itself. This usually causes data to be resubmitted on refresh. This is why form_handler files/pages are set up. Data can be posted to these via ajax or traditional form submit.

You can use session data to keep error messages etc alive for the return journey to the form page.

FORM  ->  HANDLER  --(success)-->  PAGE 6 
 ^            |
 |          (fail)             
 |            |
 |            V
 |---(set session data)

I don't know if that makes sense. It may seem like less work to send a form to itself, but that does open you up to the resubmit problem.

Thanks for the response. I'm not good at SESSIONS so that's why I haven't done it this way. I initially did have it setup to send to a separate page to INSERT those values into the DB but I wanted to keep the user on the same page incase they needed to submit multiple entries. Plus it seems more stream lined. Sending the user to a 'confirmation' page (if you will) seems unnecessary, even if it redirected back to submit form. Maybe I'll have to do it that way. But I'm SOOO CLOSE! lol I feel like I'm almost there!

Thank again. I'll look into SESSIONS. I'm just not so great and figuring out how to store and recall them.

Member Avatar for diafol

You don't have to use sessions - use cookies if you want - but that's even more of a potch if you ask me. You could also use a querystring, but this could be problematic with inputfield data (querystrings can only be 256 chars in length).

JUst this at the top of each file:

<?php
session_start();

Somewhere:

$_SESSION['postdata'] = $_POST;
(check for errors, etc and add any relevant data to the $_SESSION['postdata'] array)
header('Location: formpage.php');
exit;

IN your formpage, do a quick check for $_SESSION - if it exists, data was previously sent (accepted or not). If successful - show confirmation message.
If unsuccessful, show error message and re-enter data to the form controls (but not password fields).
You must unset the $_SESSION on this page if it is set, or this could mess up the form_handler/refresh.

if(isset($_SESSION['postdata'])){
  $postdata = $_SESSION['postdata'];
  unset($_SESSION['postdata']);
}
//keep using the data in $postdata

BTW - If you want instant feedback - use javascript (client) validation AS WELL AS php validation. If the js works as expected, php won't send a 'fail' message back to the user. However, you must have php as a last line of defence as js can be circumvented, e.g. with spoofed forms.

I got it to work! It was a mixture of johnsteve.bravo's suggestion and moving my php around. This is what I ended up with!.. Thank you for all your help!

<?php 
			
		if(array_key_exists('submit',$_POST)){
		// Fields that are on form
		$expected = array('name', 'email', 'cat', 'issue', 'descript', 'trouble', 'device', 'priority');
		// Set required fields 
		$required = array('name', 'email', 'descript', 'trouble', 'device'); 
		// Initialize array for errors 
		$errors = array(); 
						
		foreach ($_POST as $field => $value){
		// Assign to $temp and trim spaces if not array 
		$temp = is_array($value) ? $value : trim($value);
		// If field is empty and required, tag onto $errors array 
		if (empty($temp) && in_array($field, $required)) { 
		array_push($errors, $field); 
			} 
		}
						
		//If good to go
		if (empty($errors)){?> 
		<div class="green">Thank you. We will email you if we need more information or when your issue has been resolved.</div> 
		<?php
		unset($errors);
	
	 if(isset($_POST)){
		
		 $today = date("M d Y"); 

	$sql="INSERT INTO info (Ticket, Dateadded, Name, Email, Issue, Cat, Descript, Trouble, Device, Priority)
	VALUES
	('$_POST[ticket]','$today','$_POST[name]','$_POST[email]','$_POST[issue]','$_POST[cat]','$_POST[descript]','$_POST[trouble]','$_POST[device]','$_POST[priority]')";
				
		if (!mysql_query($sql,$con))
		 {
		die('Error: ' . mysql_error());
		}
		else 
		{
	$query  = "SELECT ticket, dateadded, name, email, issue, descript, cat, device, trouble, priority FROM info ORDER by ticket DESC LIMIT 1";
	$result = mysql_query($query);
				
// EMAIL Submitter Thank You message					
		while($row = mysql_fetch_array($result, MYSQL_ASSOC))
				{
					$to = "{$row['email']}";
					$subject = "UWS Support - {$row['cat']} - Ticket #{$row['ticket']}";
					$message = "Thank you for submitting a request to get this issue resolved. Your ticket # is {$row['ticket']}. You will be notified by email if we need any more information or when we've fixed this issue.\n\n Issue: {$row['issue']}\n Details: {$row['descript']}\n Device: {$row['device']}\n\n-UWS Support Team\n\n\nIf you did not submit or submitted this Ticket in error please reply to this email so that we may cancel it.";
					$from = "UWS_IT@group.example.com";
					$headers = "From: $from";
					mail($to,$subject,$message,$headers);	
				
				}
		} 
		}
							
			}
	}	
		
	
?>
Member Avatar for diafol

OK, send the form. All fine and dandy? Now press F5 on the keyboard. Still OK? Or do you get 'Post data again?' message.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.