How to INSERT into a table, part I
TAGS: SQL, INSERT, PHP, MySQL


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.

<HTML>
<BODY>

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

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

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

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

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

</TABLE>
</FORM>
</BODY>
</HTML>

And now the PHP.

<?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('127.0.0.1', 'root', 'Your_Password', 'dbname');

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

// Here we compose the SQL string
$SQL_String = "INSERT INTO contacts (
Lastname, 
Firstname, 
EmailAddr, 
WebAddr) VALUES (
'$Lastname', 
'$Firstname', 
'$EmailAddr', 
'$WebAddr')";

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

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

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:

http://127.0.0.1/myform.html


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.