PHP validating and Insert to database in one file??

Associate
Joined
6 Mar 2009
Posts
495
I have a piece of php code which validates my form which works but would now like it to insert the data to database if there are no errors.

Is it possible to do so in the one php file??

Here is my php validation.

Code:
if ($_POST['submitted']==1) {   
    $errormsg = ""; //Initialize errors   
   if ($_POST[TestTime]){   
        $TestTime = $_POST[TestTime]; //If title was entered   
    }   
   else{   
        $errormsg = "Please enter TestTime";   
    }   
    if ($_POST[PassFail]){   
       $PassFail = $_POST[PassFail]; //If comment was entered   
    }   
   else{   
        if ($errormsg){ //If there is already an error, add next error   
            $errormsg = $errormsg . " & content";   
       }else{   
           $errormsg = "Please enter content";   
        }  
			if ($errormsg){ //If any errors display them   
    			echo "<script type='text/javascript'>alert('$errormsg')</script>";

   
	} 	
    }  
		

 
}

Thanks
 
Associate
Joined
11 Mar 2007
Posts
1,741
Pah, 1 PHP file, you can do it in half a function!! Also, it's been so long since I've used direct PHP to connect to a DB I had to look up how!

...anyway, I've adjusted your code a bit and annotated it to explain what I've done. Hopefully it will prove helpful.

NOTE, I haven't tested this code so it's possible there is a small mistake that means it wont work. If it doesn't let me know and I'll go through it.

Code:
<?php
// Changed to isset().
if(isset($_POST['submitted'])){
		// Initalise our string.
		$errors = '';

	// Rather than checking if it's full or empty just check if it is empty using the empty() function and assign an error if so.
	if(empty($_POST['TestTime'])){
		// You can append to a string using .= but make sure you have initalised it first.
		$errors .= 'Please enter TestTime< br />';
	}
	if(empty($_POST['PassFail'])){
		$errors .= 'Please enter Pass Fail< br />';
	}

	// '!' means NOT. So !empty() means 'If Not empty'. So if $erros is not empty show the alert.
	if(!empty($errors)){
		echo "<script type='text/javascript'>alert('$errors')</script>";
		die;
	} else {

		// Connect to your DB. Address (normally just 'localhost'), username, password
		$con = mysql_connect("localhost","peter","abc123");

		// See if we could connect to the DB
		if(!$con) {
			die('Could not connect: ' . mysql_error());
		}

		// Select your DB
		mysql_select_db("my_db", $con);

		// Our MySql Query to insert the values. Change the table name adn field names to the ones in your DB.
		// Notice the use of 'mysql_real_escape_string', it makes User generated input safe so they can't mess with our DB.
		$query = "INSERT into YOURTABLEHERE (testtimefieldname, passfailfieldname)
					VALUES (
					'".mysql_real_escape_string($_POST['TestTime'])."',
					'".mysql_real_escape_string($_POST['PassFail'])."'
					)";

		// Run the query
		mysql_query($query)
		
		// Close the DB connection
		mysql_close($con);
		
		// Not really need as it's not in a function but good practise.
		return true;
	
	}

}
 
Associate
OP
Joined
6 Mar 2009
Posts
495
Edward01, thanks for the reply and thanks for explaining the code etc.

The only thing is that i wont insert to the database. It flags up the error message when it should but when fields are filled in it wont insert into the database. Just get a blank page with no connection error. Plus i have changed the username, password etc to my own details.

Will have another look through to see if i can find the issue. Thanks again:)
 
Associate
OP
Joined
6 Mar 2009
Posts
495
Ok got it working.

I set each variable as so:

Code:
$TestTime = mysql_real_escape_string($_POST['TestTime']);

And then just put the variable into the VALUES part.

Another quick question.

I would like the users input data to be saved if an error occurs and for it to be redirected back to the form page with their values in it. I had this working before i used the code above but cant get it working now.

All i did was add this into the input field in the form.
Code:
value="<?php echo htmlspecialchars(@$TestTime['TestTime']); ?>"

All i get is the error message and then a blank page. Would like the error to appear and then direct the user back to the form page with their values saved.
 
Associate
Joined
11 Mar 2007
Posts
1,741
Try this:

Code:
<input type="text" name="TestTime" value="<?php if($_POST) echo $_POST['TestTime'];?>" />

Simply we're looking to see if the $_POST variable has been set and if so get the value from it and output it.
 
Associate
OP
Joined
6 Mar 2009
Posts
495
Ok i have another issue that i would like a few ideas on the best way to go about it.

So basically the user will be filling in a form with testing values and if they meet the spec then it will pop up saying that the product has passed or failed. There is a column in my sql table which is Pass/Fail, so i would like the users values be be inserted into the table and then Pass or Fail to be inserted into the table depending on the test results. Can this be done??

I was thinking about getting the user to input the results, leave the Pass/Fail field empty and hit submit and then will pop up Pass/Fail and then for the form to return the values they inserted and then let the user type in either pass/fail and then all that data to be inserted into the table.

Any suggestions??
 
Back
Top Bottom