Are you displaying data that's held in an SQL database from within your own PHP program for the first time? Perhaps you have access to a database that's setup / implemented through a standard open source application such as
phpBB, the
Simple Machines Forum, or
Movable Type or be a colleague?
Here are the steps you'll need to take
1. Learn the principle
Reading data from a database is rather like reading data from a file. Just as you have lots of files on your computer, each of which can provide a stream of data, so you potentially have lots of databases / tables / requests that could provide you with streams of data. So the first things you need to do are
a) Establish a connection to whatever's providing the data from the database
b) Switch to the particular area of the database server that contains the data you want
c) Issue a query telling it exactly what you want
The query will return a "query handle" to you - that's rather like a file handle so you can then ...
d) Read back a row of data from the result set and do whatever you want with it
e) Keep repeating the previous item ( d) ) until you run out of data
2. Hand crank it
Use the
mysql program that's supplied with the database to work out the actual commands needed to run the query that you want to do, and record them carefully (cut and paste is marvellous!)
Example:
./bin/mysql -h192.168.200.199 -uwellho -pPashwurd
use wellho;
select * from placelib;
gives headings and data ...
| place | postcode | extras | distance | osref | pid |
You are then in a position to ...
3. Automate it
Translate the commands into function calls in your PHP; if you're using MySQL, those will be either
mysqli_ or
mysql function calls - later on you'll want to go via a wrapper level to make your code portable across database engines, but not at first!
Example:
mysql_connect("192.168.200.199","wellho","Pashwurd");
mysql_select_db("wellho");
mysql_query("select * from placelib where place like '%$hunt_slashed%'");
while ($row = mysql_fetch_assoc($qh)) { ... }
4. Consider the security
Having got your basic query working, consider the following very carefully:
a) Do you need to protect incoming user data from a form as you insert it into a query (see
stripslashes,
addslashes and
mysql_real_escape_string to ensure that NULL, \ and quote characters don't get passed through and leave you open to having your user cause you to generate invalid SQL ... or (worse) to modify the SQL so that it includes a malicious subcommand (this is known as an injection attack)
b) If you're handling user inputs as part of a
WHERE clause, do you need to take special action to handle any user input special characters such as
% and
_ which the
LIKE operator will see as "wildcards", but your user may wish to match exactly?
If you're using RLIKE in MySQL, you'll need to make similar consideration of the regular expression wild card characters
c) Do any of the data strings returned from the database query need to be tidied up before they're passed on to the browser - if the data may have & or < characters in it, for example, you'll need to call
htmlspecialchars or
htmlentities.
d) Are the results you get really suitable for passing back to the user, or are there fields that (s)he should not know about or will cause some sort of security leak. Is it possible for a tiny query to generate a huge result set that reveals most of a prised database to anyone who wants to see it? Be very careful not to report data from private / deleted unpubliched rows of your table. And conversely ...
e) If the user is to be given no results at all (because nothing matches!), please consider giving some feedback to highlight that fact, rather than leaving him/her staring at a blank box and wondering what went wrong.
My complete example - with each of those security issues dealt with enough to make my script strong enough to be published on the server - is
[here].
Example written during last week's
PHP course. More detailed aspects of MySQL, including the vital database design and security aspects, are covered on our
MySQL course.
(written 2010-11-07)
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
S156 - Interfacing Applications to MySQL Databases [104] mysql_connect or mysql_pconnect in PHP? - (2004-10-30)
[644] Using a MySQL database from Perl - (2006-03-13)
[663] Python to MySQL - (2006-03-31)
[723] Viewing images held in a MySQL database via PHP - (2006-05-17)
[1381] Using a MySQL database to control mod_rewrite via PHP - (2007-10-06)
[1450] Easy selection of multiple SQL conditions from PHP - (2007-11-30)
[1518] Downloading data for use in Excel (from PHP / MySQL) - (2008-01-25)
[1561] Uploading to a MySQL database through PHP - examples and common questions - (2008-03-02)
[1885] Hiding a MySQL database behind a web page - (2008-11-15)
[2263] Mysqldump fails as a cron job - a work around - (2009-06-30)
[2381] Checking the database connection manually - (2009-08-28)
[2745] Connecting Python to sqlite and MySQL databases - (2010-04-28)
[2790] Joining a MySQL table from within a Python program - (2010-06-02)
[3099] Perl - database access - DBD, DBI and DBIx modules - (2010-12-22)
[3447] Needle in a haystack - finding the web server overload - (2011-09-18)
[3455] MySQL, MySQLi, PDO or something else - how best to talk to databases from PHP - (2011-09-24)
[4436] Accessing a MySQL database from Python with mysql.connector - (2015-02-21)
H113 - Using MySQL Databases in PHP Pages [515] MySQL - an FAQ - (2005-12-03)
[572] Giving the researcher power over database analysis - (2006-01-22)
[581] Saving a MySQL query results to your local disc for Excel - (2006-01-29)
[647] Checking for MySQL errors - (2006-03-15)
[666] Database design - get it right from first principles - (2006-04-02)
[915] Paging through hundreds of entries - (2006-11-05)
[937] Display an image from a MySQL database in a web page via PHP - (2006-11-22)
[947] What is an SQL injection attack? - (2006-11-27)
[1010] Dates, times, clickable diarys in PHP - (2006-12-28)
[1983] Keeping PHP code in database and running it - (2009-01-09)
[2071] Setting up a MySQL database from PHP - (2009-03-08)
[2259] Grouping rows for a summary report - MySQL and PHP - (2009-06-27)
[2320] Helping new arrivals find out about source code examples - (2009-08-03)
[2432] Using print_r in PHP to explore mysql database requests - (2009-10-01)
[2447] MySQL stored procedures / their use on the web from PHP - (2009-10-10)
[2561] The future of MySQL - (2010-01-03)
[2628] An example of an injection attack using Javascript - (2010-02-08)
[4378] What FGW passengers want to talk about / and PHP programming to find out - (2015-01-01)
[4483] Moving from mysql to mysqli - simple worked example - (2015-05-03)
Some other Articles
Fresh Paint - Java ArraysSetting up individual variables, and arrays, in Java - some commented examplesLooking back and forward personally - 6 years each waySending out an email containing HTML from within a PHP pageHow to display information from a database within a web pageBirth Notice - Aeryn Cassandra EllisRail services back to Radstock?Coincidence, or Conspiracy - a wrong email addressGet all your ducks in a row ... and they may turn into swans Liquorice allsorts and Dolly Mixtures