Bricktowntom is committed to exceeding your expectations by providing a positive, enjoyable experience while visiting my site. Thank you for considering Bricktowntom's Market Place. I appreciate the trust you have placed in me!!
 
Displaying Data from MySQL on the Web: an Introduction

Displaying Data from MySQL on the Web: an Introduction


Displaying Data from MySQL on the Web: an Introduction

The following article is an excerpt from PHP & MySQL: Novice to Ninja, 7th Edition, a hands-on guide to learning all the tools, principles, and techniques needed to build a professional web application using PHP and MySQL. In this final tutorial in the series, you’ll learn how to take information stored in a MySQL database and display it on a web page for all to see.



This is it — the stuff you signed up for! In this chapter, you’ll learn how to take information stored in a MySQL database and display it on a web page for all to see.

So far, you’ve written your first PHP code and learned the basics of MySQL, a relational database engine, and PHP, a server-side scripting language.

Now you’re ready to learn how to use these tools together to create a website where users can view data from the database and even add their own.

Note: as in Chapter 3, I’m using “MySQL” here to refer to the database protocol. Your PHP scripts will do the same. There are numerous references in this chapter — and in the PHP code you’ll write — to “MySQL”, even though we’re actually connecting to a MariaDB database.

The Big Picture

Before we leap forward, it’s worth taking a step back for a clear picture of our ultimate goal. We have two powerful tools at our disposal: the PHP scripting language and the MySQL database engine. It’s important to understand how these will fit together.

The purpose of using MySQL for our website is to allow the content to be pulled dynamically from the database to create web pages for viewing in a regular browser. So, at one end of the system you have a visitor to your site using a web browser to request a page. That browser expects to receive a standard HTML document in return. At the other end you have the content of your site, which sits in one or more tables in a MySQL database that only understands how to respond to SQL queries (commands).

Relationships between the web server, browser, PHP and MySQL

As shown in the image above, the PHP scripting language is the go-between that speaks both languages. It processes the page request and fetches the data from the MySQL database using SQL queries just like those you used to create a table of jokes in Chapter 3. It then spits it out dynamically as the nicely formatted HTML page that the browser expects.

Just so it’s clear and fresh in your mind, this is what happens when there’s a visitor to a page on your website:

  1. The visitor’s web browser requests the web page from your web server.
  2. The web server software (typically Apache or NGINX) recognizes that the requested file is a PHP script, so the server fires up the PHP interpreter to execute the code contained in the file.
  3. Certain PHP commands (which will be the focus of this chapter) connect to the MySQL database and request the content that belongs in the web page.
  4. The MySQL database responds by sending the requested content to the PHP script.
  5. The PHP script stores the content into one or more PHP variables, then uses echo statements to output the content as part of the web page.
  6. The PHP interpreter finishes up by handing a copy of the HTML it has created to the web server.
  7. The web server sends the HTML to the web browser as it would a plain HTML file, except that instead of coming directly from an HTML file, the page is the output provided by the PHP interpreter. The browser has no way of knowing this, however. As far as the browser is concerned, it’s requesting and receiving a web page like any other.

Creating a MySQL User Account

In order for PHP to connect to your MySQL database server, it will need to use a username and password. So far, all that your joke database contains is a number of pithy bon mots, but before long it may contain sensitive information like email addresses and other private details about the users of your website. For this reason, MySQL is designed to be very secure, giving you tight control over what connections it will accept and what those connections are allowed to do.

The Docker environment already contains a MySQL user in Chapter 3, which you’ve already used to log in to the MySQL server.

You could connect to the database from your PHP script using the same username (v.je) and password (v.je), but it’s useful to create a new account — because if you have a web server, you may want to use it to host more than one website. By giving each website its own user account, you’ll have more control over who has access to the data for any given site. If you’re working with other developers, you can give them access to the sites they’re working on, but no more.

You should create a new user account with only the specific privileges it needs to work on the ijdb database that your website depends upon. Let’s do that now.

To create a user, open up MySQL Workbench and connect to your server. Then run the following queries:


CREATE USER 'ijdbuser'@'%' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON `ijdb`.* TO 'ijdbuser'@'%';

The first query is fairly self explanatory: It creates a user called ijdbuser with the password mypassword. The % sign after the username indicates that the database can be connected to from any location. The second query gives the user full acces to the ijdb schema, as a result this user can see and modify all the tables, columns and data in the ijdb schema but has no access to anything outside it.

Now that the user ijdbuser has been created, we can use it to connect to the database. It’s possible to set up a connection in MySQL Workbench with this user, but since the permissions are limited, it’s better to keep MySQL Workbench using the v.je account. Instead, we’re going to use the new user when connecting from a PHP script.

Connecting to MySQL with PHP

Before you can retrieve content from your MySQL database for inclusion in a web page, you must know how to establish a connection to MySQL from inside a PHP script. So far, you’ve used an application called MySQL Workbench to connect to your database. Just as MySQL Workbench can connect directly to a running MySQL server, so too can your own PHP scripts.

Although this chapter talks entirely about connecting to MySQL from PHP, we’re actually connecting to the MariaDB database discussed in the previous chapter. PHP can’t see any difference between MySQL and MariaDB, as they’re interchangeable. I’ll refer to the database as MySQL throughout, because all of the commands used could be used to connect to a MySQL or MariaDB database server.

The original MySQL database provided a standardized method for clients such as MySQL Workbench and PHP to communicate with the server. MariaDB copied that standard, and all the commands in PHP use the name MySQL, so to keep things simple, I’ll use the term MySQL throughout this chapter to refer to the database.

There are three methods of connecting to a MySQL server from PHP:

  • the MySQL library
  • the MySQLi library
  • the PDO library

These all essentially do the same job — connecting to the database and sending queries to it — but they use different code to achieve it.

The MySQL library is the oldest method of connecting to the database and was introduced in PHP 2.0. The features it contains are minimal, and it was superseded by MySQLi as of PHP 5.0 (released in 2004).

To connect and query the database using the old MySQL library, functions such as mysql_connect() and mysql_query() are used. These functions have been deprecated — meaning they should be avoided — since PHP 5.5, and have been removed from PHP entirely since PHP 7.0.

Although most developers saw the reason for the change as soon as PHP 5.0 was released, there are still hundreds of articles and code examples on the Web using these now non-existent mysql_* functions — despite the fact that MySQLi has effectively been the preferred library for fifteen years.

If you come across a code example that contains the line mysql_connect(), check the date of the article. It’s probably from the early 2000s, and in programming, you should never trust anything that old. Things change all the time — which is why this book is on its seventh edition!

In PHP 5.0, the MySQLi library — standing for “MySQL Improved” — was released to address some of the limitations in the original MySQL library. You can easily identify the use of MySQLi, because the code will use functions such as mysqli_connect() and mysqli_query().

Shortly after the release of the MySQLi library in PHP 5.0, PHP 5.1 was released, with a significant number of changes that helped shape the way we write PHP today (mostly to do with object-oriented programming, which you’ll see plenty of later in this book). One of the major changes in PHP 5.1 was that it introduced a third library, PDO (PHP Data Objects), for connecting to MySQL databases.

There are several differences between PDO and MySQLi, but the main one is that you can use the PDO library to connect to almost any database server — such as an Oracle server, or Microsoft SQL Server. For developers, the biggest advantage of this generic approach is that, once you’ve learned how to use the library to interact with a MySQL database, it’s very simple to interact with another database server.

Arguably, it’s simpler to write code for PDO, and there are some nuances that can make PDO code more readable — named parameters in prepared statements being the main benefit. (Don’t worry, I’ll explain what that means later on.)

For these reasons, most recent PHP projects use the PDO library, and it’s the library I’m going to show you how to use in this book. For more information on the differences, take a look at the SitePoint article “Re-introducing PDO – the Right Way to Access Databases in PHP”.

After that little history lesson, you’re probably eager to get back to writing code. Here’s how you use PDO to establish a connection to a MySQL server:

new PDO('mysql:host=hostname;dbname=database', 'username',
  'password')

For now, think of new PDO as a built-in function, just like the rand function we used in Chapter 2. If you’re thinking “Hey, functions can’t have spaces in their names!”, you’re smarter than the average bear, and I’ll explain exactly what’s going on here in a moment. In any case, it takes three arguments:

  • a string specifying the type of database (mysql:), the hostname of the server (host=hostname;), and the name of the database (dbname=database)
  • the MySQL username you want PHP to use
  • the MySQL password for that username

You may remember from Chapter 2 that PHP functions usually return a value when they’re called. This new PDO “function” returns a value called a PDO object that identifies the connection that’s been established. Since we intend to make use of the connection, we should hold onto this value by storing it in a variable. Here’s how that looks, with the necessary values filled in to connect to your database:

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');

You can probably see what’s going on with the last two arguments: they’re the username and password you created earlier in this chapter.

The first argument is a little more complicated. The dbname=ijdb part tells PDO to use the database (also referred to as a schema) called ijdb. Any query run from PHP will default to tables in that schema. SELECT * FROM joke will select records from the joke table in the ijdb schema.

Even if you’re familiar with PHP, PDO and MySQL already, the host=mysql part looks confusing. Normally, this would be host=localhost (referring to the local computer, the same machine running PHP) or pointing to a specific domain name where the database is hosted, such as host=sitepoint.com.

Why is it host=mysql, and what does mysql refer to here? In Docker, each service is given a name. If you examine the docker-compose.yml file that configures the server, the database service is called mysql, and in Docker, one service can connect to another using the other service’s name.

Arguments aside, what’s important to see here is that the value returned by new PDO is stored in a variable named $pdo.

The MySQL server is a completely separate piece of software from the web server. Therefore, we must consider the possibility that the server may be unavailable or inaccessible due to a network outage, or because the username/password combination you provided is rejected by the server, or because you just forgot to start your MySQL server! In such cases, new PDO won’t run, and will throw a PHP exception.

Note: at least by default, PHP can be configured so that no exception is thrown and it simply won’t connect. This isn’t generally desirable behavior, as it makes it much more difficult to work out what went wrong.

If you’re wondering what it means to “throw a PHP exception”, brace yourself! You’re about to discover some more features of the PHP language.

A PHP exception is what happens when you tell PHP to perform a task and it’s unable to do it. PHP will try to do what it’s told, but will fail; and in order to tell you about the failure, it will throw an exception at you. An exception is little more than PHP just crashing with a specific error message. When an exception is thrown, PHP stops. No lines of code after the error will be executed.

As a responsible developer, it’s your job to catch that exception and do something about it so the program can continue.

Note: if you don’t catch an exception, PHP will stop running your PHP script and display a spectacularly ugly error message. That error message will even reveal the code of your script that threw the error. In this case, that code contains your MySQL username and password, so it’s especially important to avoid the error message being seen by users!

To catch an exception, you should surround the code that might throw an exception with a try … catch statement:

try {
  ⋮ do something risky
}
catch (ExceptionType $e) {
  ⋮ handle the exception
}

You can think of a try … catch statement like an if … else statement, except that the second block of code is what happens if the first block of code fails to run.

Confused yet? I know I’m throwing (no pun intended) a lot of new concepts at you, but it will make more sense if I put it all together and show you what we have:

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    ’mypassword’);
  $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server.';
}

include  __DIR__ . '/../templates/output.html.php';

As you can see, this code is a try … catch statement. In the try block at the top, we attempt to connect to the database using new PDO. If this succeeds, we store the resulting PDO object in $pdo so that we can work with our new database connection. If the connection is successful, the $output variable is set to a message that will be displayed later.

Importantly, inside a try … catch statement, any code after an exception has been thrown won’t get executed. In this case, if connecting to the database throws an exception (maybe the password is wrong, or the server isn’t responding), the $output variable will never get set to “Database connection established”.

If our database connection attempt fails, PHP will throw a PDOException, which is the type of exception that new PDO throws. Our catch block, therefore, says that it will catch a PDOException (and store it in a variable named $e). Inside that block, we set the variable $output to contain a message about what went wrong.

However, this error message isn’t particularly useful. All it tells us is that PDO couldn’t connect to the database server. It would be better to have some information about why that was — for example, because the username and password were invalid.

The $e variable contains details about the exception that occurred, including an error message describing the problem. We can add this to the output variable using concatenation:

try {
  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
    'mypassword');
   $output = 'Database connection established.';
}
catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';

Note: the $e variable isn’t a string, but an object. We’ll come to what that means shortly. For now, though, all you need to know is that the code $e->getMessage() gets the error message based on the specific exception that occurred.

Like an if … else statement, one of the two branches of a try … catch statement is guaranteed to run. Either the code in the try block will execute successfully, or the code in the catch block will run. Regardless of whether the database connection was successful, there will be a message in the $output variable — either the error message, or the message saying the connection was successful.

Finally, regardless of whether the try block was successful, or the catch block runs, the template output.html.php is included. This is a generic template that just displays some text to the page:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script Output</title>
  </head>
  <body>
      <?php echo $output; ?>
  </body>
</html>

The complete code can be found in Example: MySQL-Connect.

When the template is included, it will display either the error message or the “Database connection established” message.

I hope the aforementioned code is now making some sense to you. Feel free to go back to the start of this section and read it all again if you’re lost, as there were some tricky concepts in there. Once you have a firm grip on the code, however, you’ll probably realize that I’ve still left one mystery unexplained: PDOs. Just what exactly is new PDO, and when I said it returns a “PDO object”, just what exactly is an object?

Note: all downloaded sample code includes a schema called ijdb_sample and a user called ijdb_sample, so that you’re able to run it regardless of what you called your schema and user. A file containing the database is provided as database.sql, which you can import.

If you use the web-based sample code viewer provided, the idbj_sample database will be created as you load a sample, but any changes to this schema will be lost when you view another sample. (You can mess things up, and switching to another sample and back will reset it, but if you want to keep any changes you make, make them in the schema you created.)

If you want to load the sample data into your schema using MySQL Workbench, import database.sql from the project directory by selecting Data Import/Restore. Then select Import from self-contained file, browse to database.sql, and select your schema name in default target schema. If you have created any tables with the same name, they’ll be overwritten and all records lost.

A Crash Course in Object-oriented Programming

You may have noticed the word “object” beginning to creep into my vocabulary in the previous section. PDO is the PHP Data Objects extension, and new PDO returns a PDO object. In this section, I’d like to explain what objects are all about.

Perhaps you’ve come across the term object-oriented programming (OOP) in your own explorations of PHP or of programming in general. OOP is an advanced style of programming that’s especially suited to building really complex programs with a lot of parts. Most programming languages in active use today support OOP. Some of them even require you to work in an OOP style. PHP is a little more easygoing about it, and leaves it up to the developer to decide whether or not to write their scripts in the OOP style.

So far, we’ve written our PHP code in a simpler style called procedural programming, and we’ll continue to do so for now, with a more detailed look at objects later on. Procedural style is well suited to the relatively simple projects we’re tackling at the moment. However, almost all complex projects you’ll come across use OOP, and I’ll cover it in more detail later in this book.

That said, the PDO extension we’ll use to connect to and work with a MySQL database is designed in the object-oriented programming style. This means that, rather than simply calling a function to connect to MySQL and then calling other functions that use that connection, we must first create a PDO object that will represent our database connection, and then use the features of that object to work with the database.

Creating an object is a lot like calling a function. In fact, you’ve already seen how to do it:

$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',
  'mypassword');

The new keyword tells PHP that you want to create a new object. You then leave a space and specify a class name, which tells PHP what type of object you want to create. A class is a set of instructions that PHP will follow to create an object. You can think of a class as being a recipe, such as for a cake, and an object being the actual cake that’s produced from following the recipe. Different classes can produce different objects, just as different recipes can produce different dishes.

Just as PHP comes with a bunch of built-in functions that you can call, PHP comes with a library of classes that you can create objects from. new PDO, therefore, tells PHP to create a new PDO object — that is, a new object of the built-in PDO class.

In PHP, an object is a value, just like a string, number, or array. You can store an object in a variable or pass it to a function as an argument — all the same stuff you can do with other PHP values. Objects, however, have some useful additional features.

First of all, an object behaves a lot like an array, in that it acts as a container for other values. As we saw in Chapter 2, you can access a value inside an array by specifying its index (for example, $birthdays['Kevin']). When it comes to objects, the concepts are similar but the names and code are different. Rather than accessing the value stored in an array index, we say that we’re accessing a property of the object. Instead of using square brackets to specify the name of the property we want to access, we use arrow notation (->) — for instance, $myObject->someProperty:

$myObject = new SomeClass();    // create an object
$myObject->someProperty = 123;  // set a property's value
echo $myObject->someProperty;   // get a property's value

Whereas arrays are normally used to store a list of similar values (such as an array of birthdays), objects are used to store a list of related values (for example, the properties of a database connection). Still, if that’s all objects did, there wouldn’t be much point to them: we might just as well use an array to store these values, right? Of course, objects do more.

In addition to storing a collection of properties and their values, objects can contain a group of functions designed to bring us more useful features. A function stored in an object is called a method (one of the more confusing names in the programming world, if you ask me). A method is just a function inside a class. More confusingly, when we get onto writing our own classes, methods are defined using the function keyword! Even experienced developers often wrongly use function and method interchangeably.

To call a method, we again use arrow notation — $myObject->someMethod():

$myObject = new SomeClass();    // create an object
$myObject->someMethod();        // call a method

Just like standalone functions, methods can take arguments and return values.

At this stage, this is probably all sounding a little complicated and pointless, but trust me: pulling together collections of variables (properties) and functions (methods) into little bundles called objects results in much tidier and easier-to-read code for certain tasks — working with a database being just one of them. One day, you may even want to develop custom classes that you can use to create objects of your own devising.

For now, however, we’ll stick with the classes that come included with PHP. Let’s keep working with the PDO object we’ve created, and see what we can do by calling one of its methods.

Configuring the Connection

So far, I’ve shown you how to create a PDO object to establish a connection with your MySQL database, and how to display a meaningful error message when something goes wrong:

<?php
try {
    $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser', 'mypassword');
    $output = 'Database connection established.';
} catch (PDOException $e) {
    $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';

Assuming the connection succeeds, though, you need to configure it before use. You can configure your connection by calling some methods of your new PDO object.

Before sending queries to the database, we’ll need to configure the character encoding of our database connection. As I mentioned briefly in Chapter 2, you should use UTF-8 encoded text in your websites to maximize the range of characters users have at their disposal when filling in forms on your site. By default, when PHP connects to MySQL, it uses the simpler ISO-8859-1 (or Latin-1) encoding instead of UTF-8. If we were to leave it as is, we wouldn’t easily be able to insert Chinese, Arabic or most non-English characters.

Even if you’re 100% sure that your website will only be used by English speakers, there are other problems caused by not setting the character set. If your web page is not set to UTF-8, you’ll run into problems when people write certain characters such as curly quotes into a text box, because they’ll appear in the database as a different character.

Therefore, we now need to set our new PDO object to use the UTF-8 encoding.

We can instruct PHP to use UTF-8 when querying the database by appending ;charset=utf8mb4 to the connection string. There are no downsides to doing this, provided your PHP script is also being sent to the browser as UTF-8 (which is the default in recent PHP versions):

$pdo = new PDO('mysql:host=mysql;dbname=ijdb;charset=utf8mb4', 'ijdbuser',
  'mypassword');

Note: if you go searching, you’ll find different ways to set the charset, and earlier editions of this book instructed you to use this code:

$pdo->exec('SET NAMES "utf8"');

This is because, until PHP 5.3.6, the charset option was not correctly applied by PHP. Since this is fixed in any PHP version you’re actually going to be using, setting the charset as part of the connection string is the preferred option.

The complete code we use to connect to MySQL and then configure that connection, therefore, is shown below.

Example: MySQL-Connect-Complete

<?php
try {
    $pdo = new PDO('mysql:host=mysql;dbname=ijdb;charset=utf8mb4', 'ijdbuser', 'mypassword');
    $output = 'Database connection established.';
} catch (PDOException $e) {
    $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

include  __DIR__ . '/../templates/output.html.php';

Fire up this example in your browser. (If you’ve placed your database code in index.php inside the public directory and the output.html.php file in the templates directory, the URL for the page will be https://v.je/.)

If your server is up and running, and everything is working properly, you should see a message indicating success.

A successful connection

If PHP is unable to connect to your MySQL server, or if the username and password you provided are incorrect, you’ll instead see a similar screen to that shown below. To make sure your error-handling code is working properly, you might want to misspell your password intentionally to test it out.

A connection failure

Thanks to our catch block, the error message from the database has been included on the page:

catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage();
}

The method getMessage() returns a message describing the exception that occurred. There are some other methods — including getFile() and getLine() — for returning the file name and line number that the exception was thrown on. You can generate a very detailed error message like this:

catch (PDOException $e) {
  $output = 'Unable to connect to the database server: ' . $e->getMessage() . ' in ' .
  $e->getFile() . ':' . $e->getLine();
}

This is incredibly useful if you have a large website with dozens of include files. The error message will tell you exactly which file to look in and which line the error occurred on.

If you’re curious, try inserting some other mistakes in your database connection code (for example, a misspelled database name) and observe the detailed error messages that result. When you’re done, and your database connection is working correctly, go back to the simple error message. This way, your visitors won’t be bombarded with technical gobbledygook if a genuine problem emerges with your database server.

With a connection established and a database selected, you’re ready to begin using the data stored in the database.

You might be wondering what happens to the connection with the MySQL server after the script has finished executing. If you really want to, you can force PHP to disconnect from the server by discarding the PDO object that represents your connection. You do this by setting the variable containing the object to null:

$pdo = null;  // disconnect from the database server

That said, PHP will automatically close any open database connections when it finishes running your script, so you can usually just let PHP clean up after you.

Continue reading
Displaying Data from MySQL on the Web: an Introduction
on SitePoint.

Source: Site Point

Originally posted 2022-02-10 13:52:50. Republished by Blog Post Promoter