Part 8 - Finishing The Script
Throughout this tutorial I have taught you how to use PHP to interact with a MySQL (or SQL) database and how to use the most common commands available. I have, throughout this tutorial, also shown you how to create a basic contacts management system to illustrate some of the options you can use. In this part I will show you some final MySQL tips and will give you a final version of the script.
When creating complex scripts using databases you will find that the most common thing you are doing is connecting to a database. Because of this, you can actually save time by creating either a username/password file or a connection file. For example for a username/password file you would create a file called:
and put the following in it:
Replacing the appropriate sections. Then in your php files use the following code:
at the beginning. Then, you can use the variables $username, $password and $database throughout your scripts without having to define them every time. Also, if you ever change this information, for example if you move to another web host, there is only one file to change.
You can use the same principal to connect to the database, by putting the connection code in the file, but you must always be sure to close the connection in each file or you may have problems with your MySQL server.
A limited form of searching can also be performed on your database using a built in MySQL function. This is by using the LIKE function as follows:
SELECT * FROM tablename WHERE fieldname LIKE '%$string%'
To explain furhter, LIKE tells the database to perform its 'searching' feature. The % signs mean that any other data could appear in their place and $string would hold your search string. In this place could be a word or number as well e.g.:
which would output any rows with piano in the specified field.
Similarly, you can leave out one of the % signs so that you can specify the position of the string e.g.:
Will only output rows where the specified field begins with piano, so:
The piano is next to the table.
Would not show up.
The Finished Script
Throughout this tutorial I have given you pieces of code to make a contacts database script. You can download the full script as a zip file so that you can examine the code (see Related Links).
From this tutorial you should now know the basics of using PHP and MySQL together to create database-enabled websites and programs. Using databases with the web opens up a huge new selection of things you can do and can make a simple website much more powerful, saving time updating the site, allowing user interaction and feedback and much more.
1999 - 2019 FreeWebmasterHelp.com