How to INSERT into a table, part II

Okay. So in the last posting I showed you how to read input from a form in a HTML page, and write that input to a database. Now I will show how to make everything happen in a single file. Making things a little easier and less messy.

Take all the following code, (both the HTML and the PHP), and paste it into a file named 'mynewpage.php'.


if (isset($_POST['readme']))  { 

function doread() { 

// 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'; 



<FORM METHOD='POST' ACTION='mynewpage.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' NAME='readme' VALUE='Okay, write to DB'></TD> 


Yes. It's as simple as that.
The same code, I have only changed a few things.
First as you see in the beginning we make use of isset. This will be useful later when we want to make different things happen in this same page. You may have seen pages with more than one submit button. Like a “Write” and “Edit”. These make use of the same
, but two separate submit buttons. So here at the top of the script we call a function depending on the name of the submit button pressed by the user. It's like this:

if (isset($_POST['readme']))  { 

All that happens here, is that we check for the button named “readme”, and if it is submitted, then we call the function “doread”.
So we made a small change in the HTML FORM;
<INPUT TYPE='submit' NAME='readme' VALUE='Okay, write to DB'>
Naming the submit button, so we then can recognize the button being clicked. Notice also that the ACTION in the now is pointing at the page itself.

Also we put all the existing PHP code into one function, that is done by putting the code inside two curly brackets. It look like so:

function doread() {
//.. all our code for this submit here ..

In the next blogposting I will show how to read your newly written input from the database.