Introducing Functions
Workshop Requirements
Before beginning this workshop ensure that you have the facility to upload PHP files to a PHP enabled webserver that has a MySQL database server installed. See Setting Up a Server for details on how to install one if you don't already have access.
You should also have completed the following Virtual Workshops:
- PHP Web Databases - Part 1
- PHP Web Databases - Part 2
- PHP Web Databases - Part 3
- The MySQL Series of Workshops
You should also have some experience with HTML programming.
Little Beginnings
In the last Virtual Workshop we looked at using PHP to pass a SQL statement to a MySQL database, retrieving, then displaying the data. This is obviously of limited to use to the user as there was no 'WHERE' condition to limit the output and the data displayed could extend into thousands of records. Neither can the user change the SQL statement in the script to create different 'WHERE' conditions, thus we have to create a mechanism within the script, by creating the WHERE condition, whereby the user can limit the output dynamically.
This is done by collecting a variable from an HTML form (as we did in Part 2) and including that in the SQL statement before it is passed to the MySQL database.
The HTML form
The important part of creating the HTML form is ensuring that the input field be named exactly what the variable will be called in the script. So that in the HTML the code:
<input type="text" name="artist">
can be called from the script by the array member $_POST['artist'] (as we are going to use the POST method). First create a basic HTML file called mycds.htm and put the following code, which includes a form, into it:
<html> <head> <title>Search CDs Bought by Artist</title> </head> <body bgcolor="#FFFFFF"> <h4>Search CDs Bought by Artist</h4> <p>Please enter the search term for the artist</p> <form name="cds" method="post" action="cdsbought.php"> Name of Artist: <input type="text" name="artist"> <input type="submit" name="Submit" value="ViewCds">
</form> </body> </html>
Modifying the PHP Script
Next we need to change the cdsbought.php file that we created in the last workshop, to accommodate the variable being posted to it. Look at the line:
$result = mysql_query("SELECT * FROM cd_releases", $link);
This is where we associate the SQL statement with a connection and store the result set's 'resource identifier' in a variable, which at the moment happens in one line. We will change this slightly so that we store our SQL statement in a variable (first line) and then include that variable in the mysql_query function instead of the statement (second line). This will allow us to manipulate the SQL statement independent of the mysql_query() function (and thus we need the extra line).
/* Sets the SQL Query */
$sql = "SELECT * FROM cd_releases";
/* Passes a Query to the Active Database */
$result = mysql_query($sql, $link);
Save this change and upload the file to your webspace to ensure that the script still works. This hasn't changed much, but next we are going to add a limiting condition to the SQL statement using a variable, but rather than rely on collecting the variable value from our form we will assign a temporary hard-coded value until we are sure that everything is working.
// this redefines the POST array member Artist or creates it.
$_POST['artist'] = "Christina Aguilera";
/* Sets the SQL Query */
$sql = "SELECT * FROM cd_releases";
$sql .= " WHERE (cd_releases.Artist = '{$_POST['artist']}')";
NOTE: As we are including the POST array member 'artist' in the variable string $sql we need to enclose it within braces to avoid a parse error.
Again save and upload your file and you should then see that only the Christina Aguilera cds are displayed. Next comment out the line that assigns the value to the 'artist' array member.
// this redefines the POST array member Artist or creates it.
// $_POST['artist'] = "Christina Aguilera";
We also want to add a line after closing our table that will echo the SQL statement so that we can see it working. We will also remove this later.
</table>
<?
/* Temporary ECHO of the $sql string */
echo "<p>" . $sql . "</p>";
?>
The script should now be ready to accept and process the variable sent to it by the HTML form we created. Thus the next stage is to open the mycds.htm file in a browser and test if our script works. Notice that if you put in a search term which doesn't exist, no records are returned. We will return to this problem later.
A little bit about functions
As we can see, we have already created two files to perform just one SQL task (SELECTing). If we create at least one file for each task we want to perform, this can lead to us having lots of files to maintain. An easier method is to put each SQL task into a separate PHP function within the same file and then call that function depending on what the user script is asked to do. As we currently have two files and two functions this is probably the best place to start to create one file.
The two functions are:
- To display an html form for user input (mycds.htm)
- The SQL SELECT task (cdsbought.php).
Even if we put all the code into one file we need an if statement that differentiates between what we want to do. The obvious difference is that variables are sent to the cdsbought.php file if a SELECT task is performed, thus if we check for the presence of a variable then we can determine if it is the SELECT task to be carried out or the HTML form to be displayed.
In the second part of this PHP series we saw that there was a 'Submit' variable ($_REQUEST['Submit']) generated by giving the button a name attribute as well as a value attribute. That would be a good variable to check for, using an if condition as it must exist.
if (!$_REQUEST['Submit']) {
// output HTML form
} else {
// run SELECT task
}
NOTE: We could also use another method, such as testing for the presence of ANY post or get variables, but this method has advantages that we will use later.
Creating our Functions
As we are still learning it will be better to use a new file rather than editing and modifying the old ones, so create a file called cds.php and put in the following code:
<html>
<head>
<title>CDs Bought</title>
</head>
<body>
<?php
if (!$_REQUEST['Submit']) {
echo("There is no Submit");
} else {
}
?>
</body>
</html>
Save that file, upload it, and test the script. As we haven't passed any variables the phrase 'There is no Submit' should appear. If that goes OK then we need to add our first function that will display the HTML form if this is the case. Below the if condition place the following code from the mycds.htm. As the file will be referencing itself rather than a different file change the 'action' location to use the $_SERVER['PHP_SELF'] array member.
function html_form() {
?>
<p>Please enter the search term for the artist</p>
<form name="cds" method="post" action="<? echo $_SERVER['PHP_SELF']; ?>">
Name of Artist: <input type="text" name="artist">
<input type="submit" name="Submit" value="ViewCds" />
</form>
<?
}
Next change the if condition to point towards this new function. If there has been no Submit variable passed to the server and include some code that will tell you the Submit variable is present after else.
if (!$_REQUEST['Submit']) {
html_form();
} else {
echo("There is a Submit");
}
Again save and upload the file. When we first view the script, we should be offered the HTML to enter a value into. Enter anything into the text box and then submit. If the text 'There is a Submit ' appears then this part has been carried out correctly, and we are ready to make the next function to query the database based on the value. Below the html_form() function enter the following code from the cdsbought.php file as a new select_artist() function:
function select_cd() {
?>
<h4>Cds Bought</h4>
<?
/* set's the variables for MySQL connection */
$server = "localhost:3306"; // this is the server address and port
$username = "vworksusr"; // change this to your username
$password = "vworkspass"; // change this to your password
/* Connects to the MySQL server */
$link = @mysql_connect ($server, $username, $password)
or die (mysql_error());
/* Defines the Active Database for the Connection */
if (!@mysql_select_db("cdlibrary", $link)) {
echo "<p>There has been an error. This is the error message:</p>";
echo "<p><strong>" . mysql_error() . "</strong></p>";
echo "Please Contact Your Systems Administrator with the details";
}
/* Sets the SQL Query */
$sql = "SELECT * FROM cd_releases";
$sql .= " WHERE (cd_releases.Artist = '{$_POST['artist']}')";
/* Passes a Query to the Active Database */
$result = mysql_query($sql, $link);
if (!$result) {
echo("<p>Error performing query: " . mysql_error() . "</p>");
exit();
}
/* Starts the table and creates headings */
?>
<table>
<tr>
<td><strong>Artist</strong></td>
<td><strong>Title</strong></td>
<td><strong>Year</strong></td>
<td><strong>Label</strong></td>
<td><strong>No of Tracks </strong></td>
</tr>
<?
/* Retrieves the rows from the query result set
and puts them into a HTML table row */
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo("<tr>\n<td>" . $row["Artist"] . "</td>");
echo("<td>" . $row["Title"] . "</td>");
echo("<td>" . $row["Year"] . "</td>");
echo("<td>" . $row["Label"] . "</td>");
echo("<td>" . $row["No_of_tracks"] . "</td>\n</tr>\n\n");
}
/* Closes the table */
?>
</table>
<?
/* Closes Connection to the MySQL server */
mysql_close ($link);
}
NOTE: That we don't carry forward and include the debug code we used previously.
Then we need to adapt the if condition to point to our new function
if (!$_REQUEST['Submit']) {
html_form();
} else {
select_cd();
}
A Final Nicety
When the user views the cds of an artist, to make another another selection they would have to go back to the previous page. However we can call the html_form function at end of the select_artist function. Replace this piece of code:
</table>
<?
/* Closes Connection to the MySQL server */
mysql_close ($link);
}
with this:
</table>
<?
/* Closes Connection to the MySQL server */
mysql_close ($link);
/* Displays HTML Form */
html_form();
}
which contains another call to the html_form() function to display the form ready for another query. That's enough for this section
Full Code Listing
<html>
<head>
<title>CDs Bought</title>
</head>
<body>
<h4>CDs Bought</h4>
<?php
if (!$_REQUEST['Submit']) {
html_form();
} else {
select_cd();
}
function html_form() {
?>
<p>Please enter the search term for the artist</p>
<form name="cds" method="post" action="<? echo $_SERVER['PHP_SELF']; ?>">
Name of Artist: <input type="text" name="artist">
<input type="submit" name="Submit" value="ViewCds" />
</form>
<?
}
function select_cd() {
?>
<h4>Cds Bought</h4>
<?
/* set's the variables for MySQL connection */
$server = "localhost:3306"; // this is the server address and port
$username = "username"; // change this to your username
$password = "password"; // change this to your password
/* Connects to the MySQL server */
$link = @mysql_connect ($server, $username, $password)
or die (mysql_error());
/* Defines the Active Database for the Connection */
if (!@mysql_select_db("cdlibrary", $link)) {
echo "<p>There has been an error. This is the error message:</p>";
echo "<p><strong>" . mysql_error() . "</strong></p>";
echo "Please Contact Your Systems Administrator with the details";
}
/* Sets the SQL Query */
$sql = "SELECT * FROM cd_releases";
$sql .= " WHERE (cd_releases.Artist = '{$_POST['artist']}')";
/* Passes a Query to the Active Database */
$result = mysql_query($sql, $link);
if (!$result) {
echo("<p>Error performing query: " . mysql_error() . "</p>");
exit();
}
/* Starts the table and creates headings */
?>
<table>
<tr>
<td><strong>Artist</strong></td>
<td><strong>Title</strong></td>
<td><strong>Year</strong></td>
<td><strong>Label</strong></td>
<td><strong>No of Tracks </strong></td>
</tr>
<?
/* Retrieves the rows from the query result set
and puts them into a HTML table row */
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo("<tr>\n<td>" . $row["Artist"] . "</td>");
echo("<td>" . $row["Title"] . "</td>");
echo("<td>" . $row["Year"] . "</td>");
echo("<td>" . $row["Label"] . "</td>");
echo("<td>" . $row["No_of_tracks"] . "</td>\n</tr>\n\n");
}
/* Closes the table */
?>
</table>
<?
/* Closes Connection to the MySQL server */
mysql_close ($link);
/* Displays HTML Form */
html_form();
}
?>
</body>
</html>
Lastest 10 Threads - view all
help me out
Posted By: klet at 15:34:05 on Saturday the 16th of June 2007
when do i use PHP_SELF in my html forms
great!
Posted By: budin24 at 16:59:48 on Saturday the 23rd of December 2006
Gud tuto. Hope can be more detail
doubts
Posted By: Naveenkumar at 00:02:32 on Saturday the 16th of December 2006
i am new to php and i would like to make authentication i create the html page and how could i retrive and verify the username and password is correct from database.i update all entries to database
Re: doubts
Posted By: klet at 15:32:02 on Saturday the 16th of June 2007
if you have used html form before this is quite simple, u need to use variables like $_POST,$_GET or $_REQUEST to receive the variables from the form, for example if in the form the text field is called text1, then in the php script the variable is received as either $_POST['text1'] or $_GET['text1'] depending on if you are using the GET or POST form method for sending information , otherwise $_REQUEST would work for both, try it out, but u need to know how forms pass data using either post or get methods. the different fields are referenced by their names. try it out my friend, at least it works for me.
Great
Posted By: Lena at 04:09:01 on Monday the 5th of September 2005
Very good tutorial. Thank you.
gr8
Posted By: Paul at 20:11:02 on Monday the 31st of January 2005
what a great tutorial, it worked first time. I did have a slight glitch with an error message about an undefined index. i`m not sure how i fixed it, i just made sure the html tags were correct and it resolved itself. The reason i said i`m not sure is because i dont see why an erroneous html tag would cause this message. Great work anyway!
Search Feature
Posted By: John at 04:08:15 on Monday the 19th of July 2004
Hi, how can the search be a little more 'relaxed', for example: Inputting "rob" giving the result of "Robbie Williams" and anyone else with that as part of their name? Thankyou.
Re: Search Feature
Posted By: keith at 08:04:39 on Monday the 19th of July 2004
Yes, you can use wildcards. See part 3 of this site's MySQL workshops.
Re: Re: Search Feature
Posted By: John at 09:48:03 on Monday the 19th of July 2004
I jumped the gun did I? Apart from that I'm finding your tutorial great. Thanks.
Order of Interpretation
Posted By: Robert at 13:05:10 on Tuesday the 8th of June 2004
Excellant tutorial series! I am having problems understanding the order of interpretation of PHP/HTML scripts. In this example, Introducing Functions cds.php, you constantly flip from PHP to HTML and back. Please can you give some guidence how this program is interpreted?
Re: Order of Interpretation
Posted By: keith at 13:07:49 on Tuesday the 8th of June 2004
...only the PHP blocks of code are interpreted at the server then the whole HTML output is sent to the client browser to be rendered.
HTH
K
Re: Re: Order of Interpretation
Posted By: Robert at 15:11:04 on Tuesday the 8th of June 2004
I'd got that far! Let's take the if-statement at line 10: it looks like this is the first PHP interpreted by the server (before the FORM is displayed?). Who/what fills in the value of $_REQUEST? TIA
Re: Order of Interpretation
Posted By: keith at 15:20:48 on Tuesday the 8th of June 2004
...well as the script submits to itself, this is a check to see if there has been a submission and otherwise just display the blank form. (if there has been a submission the variable will exist).
Other uses
Posted By: paul at 22:24:35 on Tuesday the 18th of May 2004
This technique is pretty cool. I wonder if one could use functions to create their own 'tag-based' language that PHP could interpret. Say you wanted to 'dumb down' php development for a class, and one built special tags like
I know it's a lot more keystrokes, but a lot of my people are more comfortable with language-based 'tags' than programming arguments. Thoughts? Or is this something that would better be created as a PHP internal or external extension?
Re: Other uses
Posted By: keith at 00:27:34 on Wednesday the 19th of May 2004
...I think that the closest that you will get to this is probably 'smarty' - http://smarty.php.net/crashcourse.php. But I don't see the point of teaching a 'dumped down php' (if I understand you correctly). If it's for a non-technical audience look at CMS?

It helps me
Posted By: Thivya at 04:59:10 on Wednesday the 15th of August 2007
it helps me...But is it possible to retrieve data from the table based on user input..example the user key in 2007 and the search function must be able to search in the date field in the table and display all the data that having 2007 as year???
Is that possible to do that?Thankx
Reply to this comment