Using Forms and a Database
Lets build a simple form in index.php
<?php |
Now if you click on tutorial on main menu you will see a form with name, address, telephone and email and a submit button. Clicking on the submit button brings you back to index.php but doesn't do anything.
Insert the following code:
| <?php // Tutorial // Created by KaotiK require('../../mainfile.php'); require(XOOPS_ROOT_PATH.'/header.php'); if (isset($_POST['submit'])){ |
Now when you click on submit you get a line of text saying "my name is: " and your name. Let me explain what is happening. The php command if is a conditional control. IF something is TRUE (for ex.) then DO something. In this case IF the form button was pressed then print the statment. The submit button is $_POST['submit'] the name 'submit' comes from the name of our button and to check if it exists I used isset which returns TRUE if it does exist and FALSE if it does not.
Now try pressing submit without filling anything. You will notice that it still prints "my name is: " but without a name. Let's create an error message if no name is filled in.
| <?php // Tutorial // Created by KaotiK require('../../mainfile.php'); require(XOOPS_ROOT_PATH.'/header.php'); if (isset($_POST['submit'])){ |
Pressing submit with an empty name now prints an error message. You will notice that I'm using an IF condition inside another IF. It's saying: if the form field named "name" is empty then print 'please fill in a name' if not (else) 'my name is: '. $_POST['name']
Putting Data into the DB
Let's take this a step further. We will now insert the form data into our DB table.
| <?php // Tutorial // Created by KaotiK require('../../mainfile.php'); require(XOOPS_ROOT_PATH.'/header.php'); if (isset($_POST['submit'])){ |
The first 4 lines of new code create variables set to form values. I've done it this way for a better understanding of what's happening. The next line $query builds the line that will be used by $xoopsDB in
| $res=$xoopsDB->query($query); |
The next line:
| if(!$res) |
checks if any error ocurred when accessing the DB. If all went fine print "Data was correctly inserted into DB!". In later tutorials I will teach you about text sanitation and it's importance.