Insert data into Database using PHP
Subject: Web development using PHP and MySQL
Here is the code for the Feedback form again with little modification.
contact.htm
Company Feedback
And below is the contactdb.php that this form is submits to
contactdb.php
Company Feedback
The PHP codes in contactdb.php is well commented.
The first line
include("conn.php"); includes the conn.php file which contains the connection string to our database.
The next set of lines contains variables that hold the values from the submitted forms
// keep the form data in variable
$names = mysqli_escape_string($conn, $_REQUEST['names']);
$email = mysqli_escape_string($conn, $_REQUEST['email']);
$comment = mysqli_escape_string($conn, $_REQUEST['comment']);
Notice that we use the mysqli_escape_string() function to clean up our entering since we cannot trust the person accessing our website from all over the world.
This was followed by another variable that hold the SQL INSERT statement
$sql="INSERT INTO feedback (name, email, comment, date_submit) VALUES ('$names','$email', '$comment',now())";
This SQL statement INSERT the values from the contact form to the feedback table.
First we specified the fields of the table (name, email, comment, date_submit) followed by the values we want to insert which are already held by their respective variables ('$names','$email', '$comment',now()).
I purposely left out
the first field (id) because we have set this field to an auto-generated number and that will be taken care of by MySQL.
The name field will store the value from the variable $names, same followed by email and comment field, the lasted date_submit field uses a built in MySQL function now() to insert the current date and time.
Finally we have the “Thank you” message in a variable $msg if the insert query is successful
if($result){
$msg = "Thanks $name for your feedback.";
}
Then the value of the $msg will now be displayed on the HTML BODY section of the file
if(isset($msg)){
// display the thanks msg
print $msg;
}
You can go ahead to test it by first accessing the contact.htm complete and submit the form.
The form would post it's data to contactdb.php which will add or insert the data to the feedback table of our bgdb database and display a thank you message on the screen.
FeedBack form
Thank you message
Record view in PhpMyAdmin
By:
Benjamin Onuorah
Login to comment or ask question on this topic
Previous Topic Next Topic