Insert data into Table through PHP


We are still using the contact.htm we use earlier, below is what it looks like once again.


Note: I have to change the ACTION attribute of this contact.htm from contact.php to the newly database version “contactdb.php” below is what I mean.

<form method="post" ACTION="contactdb.php ">
                <td colspan="2"><b>FEEDBACK FORM</b></td>
                <td><strong> Name</strong></td>
                <td><input name="names" type="text" id="names" size="30" /></td>

And below is the contactdb.php that this form is submits to

//include the connection string

// keep the form data in variable   

//store the query in a variable     
$sql="INSERT INTO feedback  VALUES ('','$name','$email', '$comment',now())";   

//execute the quesry
mysql_query($sql,$conn) or die(mysql_error());

//store the thanks msg
$msg = "Thanks ".$name." for your feedback.";
<TITLE> Company Feedback </TITLE>
// display the thanks msg
print $msg;

Just like the other PHP codes, this one is also well commented. The first line include("conn.php"); includes the conn.php file which contains the connection string to our database.
While the next set of line, contains variables that hold the values from the submitted forms element:

// keep the form data in variable   

Note the mysql_real_escape_string() is a MySQL function use  to filter or prevent attacker from entering malicious input into our database in order to hack our website, this has been a common phenomenon in website attacks. It’s commonly called Crossjacking

Therefore its important that we clean up our entering since we cannot trust the person accessing our website from all over the world.

This is also followed by another variable that hold the SQL INSERT statement

$sql="INSERT INTO feedback  VALUES ('','$name','$email', '$comment',now())";

This SQL statement INSERT the values from the contact form to the feedback table, using the structure of the table, I left the first field empty using ‘’ this is because we have set this field to an auto-generated number and that will be taken care of by the database, this is followed by the name field which will store the value from the variable $name, 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 I kept the “Thank you” message in a variable called $msg, $msg = "Thanks ".$name." for your feedback.";

Then we display or print in the BODY of the HTML print $msg;


To test this, access the contact.htm on your browser by type the URL on the address bar, for example http://localhost/bws/contact.htm

After the contact.htm has loaded, I enter some data as we have below.


When I click the Submit button the form is posted to contactdb.php which adds or inserts the data to the feedback table of our bgdb database and display a nice message on the screen as we have below.




Next »

Return to PHP Sample Main Page