Form data not passing to POST

I have a form on my index page that is linked to a php page to insert the data into my sql. When I submit the form, the data remains on the form but you see the form do something. it adds a record in my database but all variables are blank in the database. Info still shows on the form like nothing happened after submitting and nothing passes to PHP variables. Any help would be greatly appreciated.

FORM

<form action="insert.php" method="post" role="form" class="contactForm">
                      <div id="sendmessage">Your message has been sent. Thank you!</div>
                      <div id="errormessage"></div>
                      <div class="row">
                        <div class="col-md-12 mb-3">
                          <div class="form-group">
                            <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
                            <div class="validation"></div>
                          </div>
                        </div>
                        <div class="col-md-12 mb-3">
                          <div class="form-group">
                            <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
                            <div class="validation"></div>
                          </div>
                        </div>
                        <div class="col-md-12 mb-3">
                            <div class="form-group">
                              <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
                              <div class="validation"></div>
                            </div>
                        </div>
                        <div class="col-md-12 mb-3">
                          <div class="form-group">
                            <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
                            <div class="validation"></div>
                          </div>
                        </div>
                        <div class="col-md-12">
                          <button type="submit" class="button button-a button-big button-rouded" name ="insert">Send Message</button>
                        </div>
                      </div>
                    </form>

insert.php

$server = "locahost";
	$user = "user";
    $password = "";
	$dbname = "";

/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect($server,$user,$password,$dbname);
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
 
// Escape user inputs for security
$name = mysqli_real_escape_string($link, $_POST['name']);
$email = mysqli_real_escape_string($link, $_POST['email']);
$subject = mysqli_real_escape_string($link, $_POST['subject']);
$message = mysqli_real_escape_string($link, $_POST['message']);
 
// Attempt insert query execution
$sql = "INSERT INTO contact (name, email, subject, message) VALUES ('$name', '$email', '$subject','$message')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
 
// Close connection
mysqli_close($link);

Can you also post your HTML form for us to see? Thanks!

Also please use code tags…

have you tried dumping out the $_POST data?

ie: var_dump($_POST);

Sounds like you’re supplying empty data to the database. It can be something small like an typo in the $_POST names.

Could you do a print_r($_POST); or var_dump($_POST) als show us the results?

The first thing that sticks out is nothing is seeing if the request is even supposed to happen. You might want to add,

if(!$_SERVER['REQUEST_METHOD'] == 'POST')
{
    exit;
}

Otherwise, anytime that page is called it is going to add empty records, because nothing was sent over to begin with.

Next, you need prepared statements, not the stupid mysqli_real_escape_string stuff. You may also want to validate that there is even something to be inserted. If there is no name or no email, do you really want to save the record?

The code for the form is above. I am not sure if this helps but that info in the form stays after I submit. When running the var dump, I get nothing. I change the name of the submit button to submit instead of insert and added this code.

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

 print_r($_POST);
   }

It may be used in the wrong way as i am new to php so please let me know. I commented out the insert query for now until I can see something from the dump.

Thanks for your help and sorry if I misunderstand some of the questions in this forum.
Thank You

My apologies as I am not sure what you mean with code tags. I am new to PHP so I assume you mean when inserting code into this forum? Thanks for the response. I am just a beginner… sigh

Yeah I get what you are saying. I added that code (maybe incorrectly) to see if I get see a dump but I get nothing. The form data stays in the form once I submit (see response above to another person assisting). Something is preventing the post data from going anywhere but I am not sure what it might be. I changed the name of the submit button to submit just thinking that insert might conflict with the file name? Same results.

If the form data stays, that means the form isn’t being submitted to begin with, the way that this works, it submits the page and reloads, which means the page would refresh. If that isn’t happening something prevents it. Do you have javascript at all for this? Does it redirect you to the insert.php page?

Looks like you are pointing your form action to an external php script?

Why not have the query stuff in the same page as the form? and only execute upon a $_POST submission?

insert.php

So I am not using js for any of it. I am pointing it to an external php script. It is not directing me to the php file but it is submitting blank info. I am sure its something stupid that i am missing but i can;t seem to find it. index,php->insert.php with form action inset.php on submit. Does that help?

I am pointing the form to an external php script as I thought that was good practice but I am probably incorrect. Do you mean placing the post info into a variable on the same page as index and then sending that var to the index page? Sorry if I am not understanding. My thoughts were to pass the form data to an external connect and insert php script.

If you are not landing on the php page, you’re form is not being submitted. Do this to the insert.php page,

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo "<div>POST</div>";
    print_r($_POST);
}
else
{
    echo "<div>GET</div>"; 
    print_r($_GET);
}
exit();
// the rest of your code
/.../

Pass the data the same file (post to itself)…

handle any $_POST data (validate & sanitize it)…

and then do whatever with page after you succeed or fail to log to the database.

I also do -not- see any place where an actual email is being sent?

maybe something like this approach makes more sense for you:

<?
//db connection
include('../test_db_pdo.php');
//set utf8 mode
$conn->exec("set names utf8");
//set error mode
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//PDO should parameterize and sanitize good enough, but in case any screen output is needed (review page..etc)
function cleanInput($dirtyData){   
	$cleanedData = htmlspecialchars(strip_tags($dirtyData)); 
	return $cleanedData;
}
$name = isset($_POST["name"]) ? cleanInput($_POST["name"]) : '' ;
$email = isset($_POST["email"]) ? cleanInput($_POST["email"]) : '' ;
$subject = isset($_POST["subject"]) ? cleanInput($_POST["subject"]) : '' ;
$message = isset($_POST["message"]) ? cleanInput($_POST["message"]) : '' ;

//check from 'mode' and set state
$mode = isset($_GET['mode']) ? $_GET['mode'] : '';

?>
<!-- jQuery 3.3.1 -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

<!-- Scripts -->
<script type="text/javaScript"> 

	//jQuery (event actions)
	document.addEventListener("DOMContentLoaded", function(event) {		
		//enter key
		$(document).bind('keypress', function(e) {
			//enter key (code)
			if(e.keyCode==13){
				 $('#submitBtn').trigger('click');
			 }
		});			
			
		//submit button listener
		$("#submitBtn").click(function() {
			//console.log("submit button clicked");			
			
			//validation message holder
			var errormessage = '';				
			
			//any potential field validation goes here			
			//name
			if ($("#name").val() === "") {
				errormessage += "\n Please enter a name";		
			}								
			//email -> should do proper valid email format checking here as well...FYI
			if ($("#email").val() === "") {
				errormessage += "\n Please enter an email";		
			}	
			//subject
			if ($("#subject").val() === "") {
				errormessage += "\n Please enter a subject";		
			}	
			//message
			if ($("#message").val() === "") {
				errormessage += "\n Please enter a message";		
			}				
			
			//check if any errors were found
			if(errormessage != ''){
				event.preventDefault(); //do not submit form
				//output missing data
				alert("The following items need attention: \n" + errormessage);
			}else{
				//submit form
				$('#messageForm').submit();
			}			
			
			
		});
	});
					
</script>

<!-- example form -->
<?



if($mode == 'submit') {			
		$messageDetails_sql = "INSERT INTO contact (name, email, subject, message) VALUES(:name, :email, :subject, :message)";		
		$messageDetails_qryparams = array(
			':name' => $name, 
			':email' => $email, 
			':subject' => $subject, 
			':message' => $message
		);		
		$messageDetails_qry = $conn->prepare($messageDetails_sql);			
		$messageResults = $messageDetails_qry->execute($messageDetails_qryparams);
	
		if(!$messageResults){					
			//db post/insert failed.
			echo "<p>Message logging Failed</p>";					
			echo '<p>' . var_dump($messageDetails_qry->errorInfo()) . '</p>';
								
		}else{
			//save was successful
			echo '<p><strong>Message logging was successful</strong></p>';

			//build email message/string
			$emailMessage = "Message Details:" . "\r\n\r\n";			
			$emailMessage .= "Name: " .$name. "\r\n";
			$emailMessage .= "Email: " .$email. "\r\n";
			$emailMessage .= "Subject: " .$subject. "\r\n";
			$emailMessage .= "Message: " .$message. "\r\n";
			
			
			//send email
			if(mail('[email protected]', 'Subject Text', $emailBody, 'From: [email protected]')){
				echo "<p>The email transmission has failed.</p>";
			}			
		}			
	}	
	
}else{
	//display form
	?>
	<div id='formContainer'>                                
		<form id="messageForm" name="messageForm" method="post" action="<?=$_SERVER['PHP_SELF']?>?mode=submit">

			<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />

			<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
                            
			<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
                        
			<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
                            
						
			<div id="buttonContainer" name="buttonContainer">
				<br><button id="submitBtn" type="button">SEND MESSAGE</button><br>							
			</div>
		</form>
	</div>
	
	<?
}

?>

Thanks you for the help. I found that my issue was a piece of leftover code - Class=“contactform”. Now its working as expected

Thank you for the help. I will try this out but I did find the issue. I was using some leftover code that had a javascript class. Once I removed this, I was good to go. I appreciate your help!

So what piece of javascript was targeting your CSS class on that form?

Sponsor our Newsletter | Privacy Policy | Terms of Service