How to INSERT into a table, part I

In the last posting, I was showing you how to CREATE a database, and a table to go with it.
Now we will look at how to populate that database, with entries read from a form on a webpage.

First lets have a look at the HTML.


<FORM METHOD='POST' ACTION='readmyform.php'>
<TD>Firstname: </TD>
<TD><INPUT TYPE='text' NAME='firstname'></TD>

<TD>Lastname: </TD>
<TD><INPUT TYPE='text' NAME='lastname'></TD>

<TD>Email Address: </TD>
<TD><INPUT TYPE='text' NAME='emailaddr'></TD>

<TD>Homepage Address: </TD>
<TD><INPUT TYPE='text' NAME='webaddr'></TD>

<TD><INPUT TYPE='submit' VALUE='Okay, write to DB'></TD>


And now the PHP.

// Here we read the inputs from the Form
$Firstname = $_POST['firstname'];
$Lastname = $_POST['lastname'];
$EmailAddr = $_POST['emailaddr'];
$WebAddr = $_POST['webaddr'];

// Now lets connect to the database
$con = mysqli_connect('', 'root', 'Your_Password', 'dbname');

if (mysqli_connect_errno()) {
  echo "Error connecting to DB";

// Here we compose the SQL string
$SQL_String = "INSERT INTO contacts (
WebAddr) VALUES (

// Execute the query – write to the DB
$dostuff = mysqli_query($con, $SQL_String);

if(! $dostuff ) { 
echo 'Error in executing query'; 

mysqli_close ($con);

echo “Success, you have now written a row to your table”;

Save the above code in two files. The first you can name 'myform.html', copy and paste the HTML code from above into that file. Then make another file and name it 'readmyform.php', put the PHP code from above into that file and save it.
Now open your browser and write this URL:

Fill out the formfields and click on the submit button. Now you should see the line “ Success, you have now written a row to your table”.
Look at your database via phpMyAdmin. You should see the entry in the database. Remember to change the “Your_Password”, from the string connecting to the DB, into your password.

In the next posting we will look at the same code. But we will make things a little easier – I will show you how to have everything in the same file, both the HTML and the PHP coding.