{"id":92153,"date":"2026-05-14T18:02:58","date_gmt":"2026-05-14T23:02:58","guid":{"rendered":"https:\/\/www.bricktowntom.com\/blog\/?p=92153"},"modified":"2026-05-14T18:02:58","modified_gmt":"2026-05-14T23:02:58","slug":"displaying-data-from-mysql-on-the-web-an-introduction","status":"publish","type":"post","link":"https:\/\/www.bricktowntom.com\/blog\/05\/displaying-data-from-mysql-on-the-web-an-introduction.html","title":{"rendered":"Displaying Data from MySQL on the Web: an Introduction"},"content":{"rendered":"<p><a title=\"Displaying Data from MySQL on the Web: an Introduction\" href=\"https:\/\/www.sitepoint.com\/mysql-data-web\/?utm_source=rss\" rel=\"nofollow\"><br \/>\n<img data-recalc-dims=\"1\" decoding=\"async\" class=\"webfeedsFeaturedVisual\" style=\"margin: auto; margin-bottom: 5px; max-width: 100%;\" src=\"https:\/\/i0.wp.com\/uploads.sitepoint.com\/wp-content\/uploads\/2022\/01\/1643604505mysql-web.jpg?w=993&#038;ssl=1\" alt=\"Displaying Data from MySQL on the Web: an Introduction\" \/><br \/>\n<\/a><\/p>\n<p><strong>The following article is an excerpt from <em><a href=\"https:\/\/www.sitepoint.com\/premium\/books\/php-mysql-novice-to-ninja-7th-edition\">PHP &amp; MySQL: Novice to Ninja, 7th Edition<\/a><\/em>, 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\u2019ll learn how to take information stored in a MySQL database and display it on a web page for all to see.<\/strong><\/p>\n<hr style=\"margin: 1em 0 2em;\" \/>\n<ul>\n<li><a href=\"https:\/\/www.sitepoint.com\/php-development-environment\/\" target=\"_blank\" rel=\"noopener\">Server Setup and Installation<\/a><\/li>\n<li><a href=\"https:\/\/www.sitepoint.com\/php-beginners-guide\/\" target=\"_blank\" rel=\"noopener\">A Beginner\u2019s Guide to PHP<\/a><\/li>\n<li><a href=\"https:\/\/www.sitepoint.com\/introducing-mysql-a-beginners-guide\/\" target=\"_blank\" rel=\"noopener\">Introducing MySQL: A Beginner\u2019s Guide<\/a><\/li>\n<li><a href=\"https:\/\/www.sitepoint.com\/mysql-data-web\/\" target=\"_blank\" rel=\"noopener\"><strong>Displaying Data from MySQL on the Web: an Introduction<\/strong><\/a><\/li>\n<\/ul>\n<hr style=\"margin: 1em 0 2em;\" \/>\n<p>This is it \u2014 the stuff you signed up for! In this chapter, you\u2019ll learn how to take information stored in a MySQL database and display it on a web page for all to see.<\/p>\n<p>So far, you\u2019ve written your first PHP code and learned the basics of MySQL, a relational database engine, and PHP, a server-side scripting language.<\/p>\n<p>Now you\u2019re 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.<\/p>\n<p><em>Note: as in Chapter 3, I\u2019m using \u201cMySQL\u201d here to refer to the database protocol. Your PHP scripts will do the same. There are numerous references in this chapter \u2014 and in the PHP code you\u2019ll write \u2014 to \u201cMySQL\u201d, even though we\u2019re actually connecting to a MariaDB database.<\/em><\/p>\n<h2 id=\"the-big-picture\">The Big Picture<\/h2>\n<p>Before we leap forward, it\u2019s 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\u2019s important to understand how these will fit together.<\/p>\n<p>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).<\/p>\n<p><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/uploads.sitepoint.com\/wp-content\/uploads\/2022\/01\/1643516419First_Principles.png?w=993&#038;ssl=1\" alt=\"Relationships between the web server, browser, PHP and MySQL\" \/><\/p>\n<p>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.<\/p>\n<p>Just so it\u2019s clear and fresh in your mind, this is what happens when there\u2019s a visitor to a page on your website:<\/p>\n<ol>\n<li>The visitor\u2019s web browser requests the web page from your web server.<\/li>\n<li>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.<\/li>\n<li>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.<\/li>\n<li>The MySQL database responds by sending the requested content to the PHP script.<\/li>\n<li>The PHP script stores the content into one or more PHP variables, then uses <code>echo<\/code> statements to output the content as part of the web page.<\/li>\n<li>The PHP interpreter finishes up by handing a copy of the HTML it has created to the web server.<\/li>\n<li>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\u2019s requesting and receiving a web page like any other.<\/li>\n<\/ol>\n<h2 id=\"creating-a-mysql-user-account\">Creating a MySQL User Account<\/h2>\n<p>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 <em>bon mots<\/em>, 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.<\/p>\n<p>The Docker environment already contains a MySQL user in Chapter 3, which you\u2019ve already used to log in to the MySQL server.<\/p>\n<p>You <em>could<\/em> connect to the database from your PHP script using the same username (<code>v.je<\/code>) and password (<code>v.je<\/code>), but it\u2019s useful to create a new account \u2014 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\u2019ll have more control over who has access to the data for any given site. If you\u2019re working with other developers, you can give them access to the sites they\u2019re working on, but no more.<\/p>\n<p>You should create a new user account with only the specific privileges it needs to work on the <code>ijdb<\/code> database that your website depends upon. Let\u2019s do that now.<\/p>\n<p>To create a user, open up MySQL Workbench and connect to your server. Then run the following queries:<\/p>\n<pre><code class=\"lang-sql\">\r\nCREATE USER 'ijdbuser'@'%' IDENTIFIED BY 'mypassword';\r\nGRANT ALL PRIVILEGES ON `ijdb`.* TO 'ijdbuser'@'%';\r\n<\/code><\/pre>\n<p>The first query is fairly self explanatory: It creates a user called <code>ijdbuser<\/code> with the password <code>mypassword<\/code>. The <code>%<\/code> 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 <code>ijdb<\/code> schema, as a result this user can see and modify all the tables, columns and data in the <code>ijdb<\/code> schema but has no access to anything outside it.<\/p>\n<p>Now that the user <code>ijdbuser<\/code> has been created, we can use it to connect to the database. It\u2019s possible to set up a connection in MySQL Workbench with this user, but since the permissions are limited, it\u2019s better to keep MySQL Workbench using the <code>v.je<\/code> account. Instead, we\u2019re going to use the new user when connecting from a PHP script.<\/p>\n<h2 id=\"connecting-to-mysql-with-php\">Connecting to MySQL with PHP<\/h2>\n<p>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\u2019ve 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.<\/p>\n<p>Although this chapter talks entirely about connecting to MySQL from PHP, we\u2019re actually connecting to the MariaDB database discussed in the previous chapter. PHP can\u2019t see any difference between MySQL and MariaDB, as they\u2019re interchangeable. I\u2019ll 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.<\/p>\n<p>The original MySQL database provided a standardized method for <em>clients<\/em> such as MySQL Workbench and PHP to communicate with the server. MariaDB copied that standard, and all the commands in PHP use the name <em>MySQL<\/em>, so to keep things simple, I\u2019ll use the term <em>MySQL<\/em> throughout this chapter to refer to the database.<\/p>\n<p>There are three methods of connecting to a MySQL server from PHP:<\/p>\n<ul>\n<li>the MySQL library<\/li>\n<li>the MySQLi library<\/li>\n<li>the PDO library<\/li>\n<\/ul>\n<p>These all essentially do the same job \u2014 connecting to the database and sending queries to it \u2014 but they use different code to achieve it.<\/p>\n<p>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).<\/p>\n<p>To connect and query the database using the old MySQL library, functions such as <code>mysql_connect()<\/code> and <code>mysql_query()<\/code> are used. These functions have been <strong>deprecated<\/strong> \u2014 meaning they should be avoided \u2014 since PHP 5.5, and have been removed from PHP entirely since PHP 7.0.<\/p>\n<p>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 <code>mysql_*<\/code> functions \u2014 despite the fact that MySQLi has effectively been the preferred library for fifteen years.<\/p>\n<p>If you come across a code example that contains the line <code>mysql_connect()<\/code>, check the date of the article. It\u2019s probably from the early 2000s, and in programming, you should never trust anything that old. Things change all the time \u2014 which is why this book is on its seventh edition!<\/p>\n<p>In PHP 5.0, the MySQLi library \u2014 standing for \u201cMySQL Improved\u201d \u2014 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 <code>mysqli_connect()<\/code> and <code>mysqli_query()<\/code>.<\/p>\n<p>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\u2019ll 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.<\/p>\n<p>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 \u2014 such as an Oracle server, or Microsoft SQL Server. For developers, the biggest advantage of this generic approach is that, once you\u2019ve learned how to use the library to interact with a MySQL database, it\u2019s very simple to interact with another database server.<\/p>\n<p>Arguably, it\u2019s simpler to write code for PDO, and there are some nuances that can make PDO code more readable \u2014 named parameters in prepared statements being the main benefit. (Don\u2019t worry, I\u2019ll explain what that means later on.)<\/p>\n<p>For these reasons, most recent PHP projects use the PDO library, and it\u2019s the library I\u2019m going to show you how to use in this book. For more information on the differences, take a look at the SitePoint article \u201c<a href=\"https:\/\/www.sitepoint.com\/re-introducing-pdo-the-right-way-to-access-databases-in-php\/\">Re-introducing PDO \u2013 the Right Way to Access Databases in PHP<\/a>\u201d.<\/p>\n<p>After that little history lesson, you\u2019re probably eager to get back to writing code. Here\u2019s how you use PDO to establish a connection to a MySQL server:<\/p>\n<pre><code class=\"lang-php\">new PDO('mysql:host=hostname;dbname=database', 'username',\r\n  'password')\r\n<\/code><\/pre>\n<p>For now, think of <code>new PDO<\/code> as a built-in function, just like the <code>rand<\/code> function we used in Chapter 2. If you\u2019re thinking \u201cHey, functions can\u2019t have <em>spaces<\/em> in their names!\u201d, you\u2019re smarter than the average bear, and I\u2019ll explain exactly what\u2019s going on here in a moment. In any case, it takes three arguments:<\/p>\n<ul>\n<li>a string specifying the type of database (<code>mysql:<\/code>), the hostname of the server (<code>host=hostname;<\/code>), and the name of the database (<code>dbname=database<\/code>)<\/li>\n<li>the MySQL username you want PHP to use<\/li>\n<li>the MySQL password for that username<\/li>\n<\/ul>\n<p>You may remember from Chapter 2 that PHP functions usually return a value when they\u2019re called. This <code>new PDO<\/code> \u201cfunction\u201d returns a value called a <code>PDO<\/code> object that identifies the connection that\u2019s been established. Since we intend to make use of the connection, we should hold onto this value by storing it in a variable. Here\u2019s how that looks, with the necessary values filled in to connect to your database:<\/p>\n<pre><code class=\"lang-php\">$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',\r\n  'mypassword');\r\n<\/code><\/pre>\n<p>You can probably see what\u2019s going on with the last two arguments: they\u2019re the username and password you created earlier in this chapter.<\/p>\n<p>The first argument is a little more complicated. The <code>dbname=ijdb<\/code> part tells PDO to use the database (also referred to as a <em>schema<\/em>) called <code>ijdb<\/code>. Any query run from PHP will default to tables in that schema. <code>SELECT * FROM joke<\/code> will select records from the <code>joke<\/code> table in the <code>ijdb<\/code> schema.<\/p>\n<p>Even if you\u2019re familiar with PHP, PDO and MySQL already, the <code>host=mysql<\/code> part looks confusing. Normally, this would be <code>host=localhost<\/code> (referring to the local computer, the same machine running PHP) or pointing to a specific domain name where the database is hosted, such as <code>host=sitepoint.com<\/code>.<\/p>\n<p>Why is it <code>host=mysql<\/code>, and what does <code>mysql<\/code> refer to here? In Docker, each <em>service<\/em> is given a name. If you examine the <code>docker-compose.yml<\/code> file that configures the server, the database service is called <code>mysql<\/code>, and in Docker, one service can connect to another using the other service\u2019s name.<\/p>\n<p>Arguments aside, what\u2019s important to see here is that the value returned by <code>new PDO<\/code> is stored in a variable named <code>$pdo<\/code>.<\/p>\n<p>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, <code>new PDO<\/code> won\u2019t run, and will throw a PHP exception.<\/p>\n<p><em>Note: at least by default, PHP can be configured so that no exception is thrown and it simply won\u2019t connect. This isn\u2019t generally desirable behavior, as it makes it much more difficult to work out what went wrong.<\/em><\/p>\n<p>If you\u2019re wondering what it means to \u201cthrow a PHP exception\u201d, brace yourself! You\u2019re about to discover some more features of the PHP language.<\/p>\n<p>A PHP <strong>exception<\/strong> is what happens when you tell PHP to perform a task and it\u2019s unable to do it. PHP will try to do what it\u2019s 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.<\/p>\n<p>As a responsible developer, it\u2019s your job to catch that exception and do something about it so the program can continue.<\/p>\n<p><em>Note: if you don\u2019t 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\u2019s especially important to avoid the error message being seen by users!<\/em><\/p>\n<p>To catch an exception, you should surround the code that might throw an exception with a <code>try \u2026 catch<\/code> statement:<\/p>\n<pre><code class=\"lang-php\">try {\r\n  \u22ee do something risky\r\n}\r\ncatch (ExceptionType $e) {\r\n  \u22ee handle the exception\r\n}\r\n<\/code><\/pre>\n<p>You can think of a <code>try \u2026 catch<\/code> statement like an <code>if \u2026 else<\/code> statement, except that the second block of code is what happens if the first block of code fails to run.<\/p>\n<p>Confused yet? I know I\u2019m 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:<\/p>\n<pre><code class=\"lang-php\">try {\r\n  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',\r\n    \u2019mypassword\u2019);\r\n  $output = 'Database connection established.';\r\n}\r\ncatch (PDOException $e) {\r\n  $output = 'Unable to connect to the database server.';\r\n}\r\n\r\ninclude  __DIR__ . '\/..\/templates\/output.html.php';\r\n<\/code><\/pre>\n<p>As you can see, this code is a <code>try \u2026 catch<\/code> statement. In the <code>try<\/code> block at the top, we attempt to connect to the database using <code>new PDO<\/code>. If this succeeds, we store the resulting PDO object in <code>$pdo<\/code> so that we can work with our new database connection. If the connection is successful, the <code>$output<\/code> variable is set to a message that will be displayed later.<\/p>\n<p>Importantly, inside a <code>try \u2026 catch<\/code> statement, any code after an exception has been thrown won\u2019t get executed. In this case, if connecting to the database throws an exception (maybe the password is wrong, or the server isn\u2019t responding), the <code>$output<\/code> variable will never get set to \u201cDatabase connection established\u201d.<\/p>\n<p>If our database connection attempt fails, PHP will throw a <code>PDOException<\/code>, which is the type of exception that <code>new PDO<\/code> throws. Our <code>catch<\/code> block, therefore, says that it will catch a PDOException (and store it in a variable named <code>$e<\/code>). Inside that block, we set the variable <code>$output<\/code> to contain a message about what went wrong.<\/p>\n<p>However, this error message isn\u2019t particularly useful. All it tells us is that PDO couldn\u2019t connect to the database server. It would be better to have some information about why that was \u2014 for example, because the username and password were invalid.<\/p>\n<p>The <code>$e<\/code> 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:<\/p>\n<pre><code class=\"lang-php\">try {\r\n  $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',\r\n    'mypassword');\r\n   $output = 'Database connection established.';\r\n}\r\ncatch (PDOException $e) {\r\n  $output = 'Unable to connect to the database server: ' . $e-&gt;getMessage();\r\n}\r\n\r\ninclude  __DIR__ . '\/..\/templates\/output.html.php';\r\n<\/code><\/pre>\n<p><em>Note: the <code>$e<\/code> variable isn\u2019t a string, but an <strong>object<\/strong>. We\u2019ll come to what that means shortly. For now, though, all you need to know is that the code <code>$e-&gt;getMessage()<\/code> gets the error message based on the specific exception that occurred.<\/em><\/p>\n<p>Like an <code>if \u2026 else<\/code> statement, one of the two branches of a <code>try \u2026 catch<\/code> statement is guaranteed to run. Either the code in the <code>try<\/code> block will execute successfully, or the code in the <code>catch<\/code> block will run. Regardless of whether the database connection was successful, there will be a message in the <code>$output<\/code> variable \u2014 either the error message, or the message saying the connection was successful.<\/p>\n<p>Finally, regardless of whether the <code>try<\/code> block was successful, or the <code>catch<\/code> block runs, the template <code>output.html.php<\/code> is included. This is a generic template that just displays some text to the page:<\/p>\n<pre><code class=\"lang-html\">&lt;!doctype html&gt;\r\n&lt;html&gt;\r\n  &lt;head&gt;\r\n    &lt;meta charset=\"utf-8\"&gt;\r\n    &lt;title&gt;Script Output&lt;\/title&gt;\r\n  &lt;\/head&gt;\r\n  &lt;body&gt;\r\n      &lt;?php echo $output; ?&gt;\r\n  &lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/code><\/pre>\n<p>The complete code can be found in <strong>Example: <a href=\"https:\/\/github.com\/spbooks\/phpmysql7\/tree\/MySQL-Connect\">MySQL-Connect<\/a><\/strong>.<\/p>\n<p>When the template is included, it will display either the error message or the \u201cDatabase connection established\u201d message.<\/p>\n<p>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\u2019re lost, as there were some tricky concepts in there. Once you have a firm grip on the code, however, you\u2019ll probably realize that I\u2019ve still left one mystery unexplained: PDOs. Just what exactly is <code>new PDO<\/code>, and when I said it returns a \u201cPDO object\u201d, just what exactly is an object?<\/p>\n<p><em>Note: all downloaded sample code includes a schema called <code>ijdb_sample<\/code> and a user called <code>ijdb_sample<\/code>, so that you\u2019re able to run it regardless of what you called your schema and user. A file containing the database is provided as <code>database.sql<\/code>, which you can import.<\/em><\/p>\n<p><em>If you use the web-based sample code viewer provided, the <code>idbj_sample<\/code> 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.)<\/em><\/p>\n<p><em>If you want to load the sample data into your schema using MySQL Workbench, import <code>database.sql<\/code> from the <code>project<\/code> directory by selecting <strong>Data Import\/Restore<\/strong>. Then select <strong>Import from self-contained file<\/strong>, browse to <code>database.sql<\/code>, and select your schema name in <strong>default<\/strong> target schema. If you have created any tables with the same name, they\u2019ll be overwritten and all records lost.<\/em><\/p>\n<h2 id=\"a-crash-course-in-object-oriented-programming\">A Crash Course in Object-oriented Programming<\/h2>\n<p>You may have noticed the word \u201cobject\u201d beginning to creep into my vocabulary in the previous section. PDO is the PHP Data <em>Objects<\/em> extension, and <code>new PDO<\/code> returns a PDO <em>object<\/em>. In this section, I\u2019d like to explain what objects are all about.<\/p>\n<p>Perhaps you\u2019ve come across the term <strong>object-oriented programming (OOP)<\/strong> in your own explorations of PHP or of programming in general. OOP is an advanced style of programming that\u2019s 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 <em>require<\/em> 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.<\/p>\n<p>So far, we\u2019ve written our PHP code in a simpler style called <strong>procedural programming<\/strong>, and we\u2019ll 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\u2019re tackling at the moment. However, almost all complex projects you\u2019ll come across use OOP, and I\u2019ll cover it in more detail later in this book.<\/p>\n<p>That said, the PDO extension we\u2019ll 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 <em>object<\/em> that will represent our database connection, and then use the features of that object to work with the database.<\/p>\n<p>Creating an object is a lot like calling a function. In fact, you\u2019ve already seen how to do it:<\/p>\n<pre><code class=\"lang-php\">$pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser',\r\n  'mypassword');\r\n<\/code><\/pre>\n<p>The <code>new<\/code> keyword tells PHP that you want to create a new object. You then leave a space and specify a <strong>class name<\/strong>, which tells PHP what type of object you want to create. A <strong>class<\/strong> 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\u2019s produced from following the recipe. Different classes can produce different objects, just as different recipes can produce different dishes.<\/p>\n<p>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. <code>new PDO<\/code>, therefore, tells PHP to create a new <code>PDO<\/code> object \u2014 that is, a new object of the built-in <code>PDO<\/code> class.<\/p>\n<p>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 \u2014 all the same stuff you can do with other PHP values. Objects, however, have some useful additional features.<\/p>\n<p>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, <code>$birthdays['Kevin']<\/code>). 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\u2019re accessing a <strong>property<\/strong> of the object. Instead of using square brackets to specify the name of the property we want to access, we use <strong>arrow notation<\/strong> (<code>-&gt;<\/code>) \u2014 for instance, <code>$myObject-&gt;someProperty<\/code>:<\/p>\n<pre><code class=\"lang-php\">$myObject = new SomeClass();    \/\/ create an object\r\n$myObject-&gt;someProperty = 123;  \/\/ set a property's value\r\necho $myObject-&gt;someProperty;   \/\/ get a property's value\r\n<\/code><\/pre>\n<p>Whereas arrays are normally used to store a list of <em>similar<\/em> values (such as an array of birthdays), objects are used to store a list of <em>related<\/em> values (for example, the properties of a database connection). Still, if that\u2019s all objects did, there wouldn\u2019t be much point to them: we might just as well use an array to store these values, right? Of course, objects do more.<\/p>\n<p>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 <strong>method<\/strong> (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 <code>function<\/code> keyword! Even experienced developers often wrongly use <em>function<\/em> and <em>method<\/em> interchangeably.<\/p>\n<p>To call a method, we again use arrow notation \u2014 <code>$myObject-&gt;someMethod()<\/code>:<\/p>\n<pre><code class=\"lang-php\">$myObject = new SomeClass();    \/\/ create an object\r\n$myObject-&gt;someMethod();        \/\/ call a method\r\n<\/code><\/pre>\n<p>Just like standalone functions, methods can take arguments and return values.<\/p>\n<p>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 \u2014 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.<\/p>\n<p>For now, however, we\u2019ll stick with the classes that come included with PHP. Let\u2019s keep working with the <code>PDO<\/code> object we\u2019ve created, and see what we can do by calling one of its methods.<\/p>\n<h3 id=\"configuring-the-connection\">Configuring the Connection<\/h3>\n<p>So far, I\u2019ve shown you how to create a <code>PDO<\/code> object to establish a connection with your MySQL database, and how to display a meaningful error message when something goes wrong:<\/p>\n<pre><code class=\"lang-php\">&lt;?php\r\ntry {\r\n    $pdo = new PDO('mysql:host=mysql;dbname=ijdb', 'ijdbuser', 'mypassword');\r\n    $output = 'Database connection established.';\r\n} catch (PDOException $e) {\r\n    $output = 'Unable to connect to the database server: ' . $e-&gt;getMessage();\r\n}\r\n\r\ninclude  __DIR__ . '\/..\/templates\/output.html.php';\r\n<\/code><\/pre>\n<p>Assuming the connection succeeds, though, you need to configure it before use. You can configure your connection by calling some methods of your new <code>PDO<\/code> object.<\/p>\n<p>Before sending queries to the database, we\u2019ll 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\u2019t easily be able to insert Chinese, Arabic or most non-English characters.<\/p>\n<p>Even if you\u2019re 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\u2019ll run into problems when people write certain characters such as curly quotes <code>\u201d<\/code> into a text box, because they\u2019ll appear in the database as a different character.<\/p>\n<p>Therefore, we now need to set our new <code>PDO<\/code> object to use the UTF-8 encoding.<\/p>\n<p>We can instruct PHP to use UTF-8 when querying the database by appending <code>;charset=utf8mb4<\/code> to the connection string. There are no downsides to doing this, provided your PHP script is also being sent to the browser as <code>UTF-8<\/code> (which is the default in recent PHP versions):<\/p>\n<pre><code class=\"lang-php\">$pdo = new PDO('mysql:host=mysql;dbname=ijdb;charset=utf8mb4', 'ijdbuser',\r\n  'mypassword');\r\n<\/code><\/pre>\n<p><em>Note: if you go searching, you\u2019ll find different ways to set the charset, and earlier editions of this book instructed you to use this code:<\/em><\/p>\n<pre><code class=\"language-php\">$pdo-&gt;exec('SET NAMES \"utf8\"');<\/code><\/pre>\n<p><em>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\u2019re actually going to be using, setting the charset as part of the connection string is the preferred option.<\/em><\/p>\n<p>The complete code we use to connect to MySQL and then configure that connection, therefore, is shown below.<\/p>\n<p><strong>Example: <a href=\"https:\/\/github.com\/spbooks\/phpmysql7\/tree\/MySQL-Connect-Complete\">MySQL-Connect-Complete<\/a><\/strong><\/p>\n<pre><code class=\"lang-php\">&lt;?php\r\ntry {\r\n    $pdo = new PDO('mysql:host=mysql;dbname=ijdb;charset=utf8mb4', 'ijdbuser', 'mypassword');\r\n    $output = 'Database connection established.';\r\n} catch (PDOException $e) {\r\n    $output = 'Unable to connect to the database server: ' . $e-&gt;getMessage();\r\n}\r\n\r\ninclude  __DIR__ . '\/..\/templates\/output.html.php';\r\n<\/code><\/pre>\n<p>Fire up this example in your browser. (If you\u2019ve placed your database code in <code>index.php<\/code> inside the <code>public<\/code> directory and the <code>output.html.php<\/code> file in the <code>templates<\/code> directory, the URL for the page will be <code>https:\/\/v.je\/<\/code>.)<\/p>\n<p>If your server is up and running, and everything is working properly, you should see a message indicating success.<\/p>\n<p><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/uploads.sitepoint.com\/wp-content\/uploads\/2022\/01\/1643516445connect-success.png?w=993&#038;ssl=1\" alt=\"A successful connection\" \/><\/p>\n<p>If PHP is unable to connect to your MySQL server, or if the username and password you provided are incorrect, you\u2019ll 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.<\/p>\n<p><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/uploads.sitepoint.com\/wp-content\/uploads\/2022\/01\/1643516472connect-failure.png?w=993&#038;ssl=1\" alt=\"A connection failure\" \/><\/p>\n<p>Thanks to our <code>catch<\/code> block, the error message from the database has been included on the page:<\/p>\n<pre><code class=\"lang-php\">catch (PDOException $e) {\r\n  $output = 'Unable to connect to the database server: ' . $e-&gt;getMessage();\r\n}\r\n<\/code><\/pre>\n<p>The method <code>getMessage()<\/code> returns a message describing the exception that occurred. There are some other methods \u2014 including <code>getFile()<\/code> and <code>getLine()<\/code> \u2014 for returning the file name and line number that the exception was thrown on. You can generate a very detailed error message like this:<\/p>\n<pre><code class=\"lang-php\">catch (PDOException $e) {\r\n  $output = 'Unable to connect to the database server: ' . $e-&gt;getMessage() . ' in ' .\r\n  $e-&gt;getFile() . ':' . $e-&gt;getLine();\r\n}\r\n<\/code><\/pre>\n<p>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.<\/p>\n<p>If you\u2019re 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\u2019re done, and your database connection is working correctly, go back to the simple error message. This way, your visitors won\u2019t be bombarded with technical gobbledygook if a genuine problem emerges with your database server.<\/p>\n<p>With a connection established and a database selected, you\u2019re ready to begin using the data stored in the database.<\/p>\n<p><em>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 <code>PDO<\/code> object that represents your connection. You do this by setting the variable containing the object to <code>null<\/code>:<\/em><\/p>\n<pre><code class=\"language-php\">$pdo = null;  \/\/ disconnect from the database server<\/code><\/pre>\n<p><em>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.<\/em><\/p>\n<p>Continue reading<br \/>\n<a href=\"https:\/\/www.sitepoint.com\/mysql-data-web\/?utm_source=rss\" rel=\"nofollow\">Displaying Data from MySQL on the Web: an Introduction<\/a><br \/>\non <a href=\"https:\/\/www.sitepoint.com\" rel=\"nofollow\">SitePoint<\/a>.<\/p>\n<p>Source: Site Point<\/p>\n<p id=\"kc_opp\"><small>Republished by  <a href=\"http:\/\/www.blogtrafficexchange.com\/\">Blog Post Promoter<\/a><\/small><\/p>","protected":false},"excerpt":{"rendered":"<p>The following article is an excerpt from PHP &amp; MySQL: Novice to Ninja, 7th Edition, a hands-on guide to learning all the tools, &hellip;<\/p>\n","protected":false},"author":1,"featured_media":92154,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[23511],"tags":[128],"class_list":["post-92153","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ebusiness-emarketing","tag-advantage"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604505mysql-web.jpg?fit=1200%2C680&ssl=1","jetpack_shortlink":"https:\/\/wp.me\/p3k0YU-nYl","jetpack-related-posts":[{"id":92155,"url":"https:\/\/www.bricktowntom.com\/blog\/04\/introducing-mysql-a-beginners-guide.html","url_meta":{"origin":92153,"position":0},"title":"Introducing MySQL: A Beginner\u2019s Guide","author":"admin","date":"April 21, 2026","format":false,"excerpt":"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 tutorial, you\u2019ll learn what a database is, and how to work\u2026","rel":"","context":"In &quot;E-business &amp; E-marketing&quot;","block_context":{"text":"E-business &amp; E-marketing","link":"https:\/\/www.bricktowntom.com\/blog\/category\/ebusiness-emarketing"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604354mysql-introduction.jpg?fit=1200%2C680&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604354mysql-introduction.jpg?fit=1200%2C680&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604354mysql-introduction.jpg?fit=1200%2C680&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604354mysql-introduction.jpg?fit=1200%2C680&ssl=1&resize=700%2C400 2x, https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604354mysql-introduction.jpg?fit=1200%2C680&ssl=1&resize=1050%2C600 3x"},"classes":[]},{"id":92159,"url":"https:\/\/www.bricktowntom.com\/blog\/05\/setting-up-your-php-development-environment-with-docker.html","url_meta":{"origin":92153,"position":1},"title":"Setting Up Your PHP Development Environment with Docker","author":"admin","date":"May 7, 2026","format":false,"excerpt":"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 tutorial, we cover how to set up a web server with\u2026","rel":"","context":"In &quot;E-business &amp; E-marketing&quot;","block_context":{"text":"E-business &amp; E-marketing","link":"https:\/\/www.bricktowntom.com\/blog\/category\/ebusiness-emarketing"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604106php-mysql-install.jpg?fit=1200%2C680&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604106php-mysql-install.jpg?fit=1200%2C680&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604106php-mysql-install.jpg?fit=1200%2C680&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604106php-mysql-install.jpg?fit=1200%2C680&ssl=1&resize=700%2C400 2x, https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604106php-mysql-install.jpg?fit=1200%2C680&ssl=1&resize=1050%2C600 3x"},"classes":[]},{"id":93169,"url":"https:\/\/www.bricktowntom.com\/blog\/05\/cheat-sheet-web-hosting-plus.html","url_meta":{"origin":92153,"position":2},"title":"Cheat Sheet: Web Hosting Plus","author":"admin","date":"May 4, 2026","format":false,"excerpt":"Now, hosting that\u2019s faster \u2014 and better.\u00a0 Web Hosting Plus is for new or growing sites that require greater performance, security and typically see higher traffic. You might be powering sophisticated ecommerce sites or hosting videos. However, you don\u2019t want the added complexity of managing a server.\u00a0Web Hosting Plus\u00a0is the\u2026","rel":"","context":"In &quot;E-business &amp; E-marketing&quot;","block_context":{"text":"E-business &amp; E-marketing","link":"https:\/\/www.bricktowntom.com\/blog\/category\/ebusiness-emarketing"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":92868,"url":"https:\/\/www.bricktowntom.com\/blog\/05\/cheat-sheet-web-hosting.html","url_meta":{"origin":92153,"position":3},"title":"Cheat sheet: Web Hosting","author":"admin","date":"May 6, 2026","format":false,"excerpt":"Web Hosting that scales with your needs. With a 99.9% uptime guarantee, you\u2019ll enjoy unmetered bandwidth, superior performance, and nimble load times. Build your client\u2019s site quickly on a platform you can trust. GoDaddy\u2019s Web Hosting is for web designers and developers who need to launch and grow a web\u2026","rel":"","context":"In &quot;E-business &amp; E-marketing&quot;","block_context":{"text":"E-business &amp; E-marketing","link":"https:\/\/www.bricktowntom.com\/blog\/category\/ebusiness-emarketing"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":92157,"url":"https:\/\/www.bricktowntom.com\/blog\/05\/introducing-php-a-beginners-guide.html","url_meta":{"origin":92153,"position":4},"title":"Introducing PHP: A Beginner\u2019s Guide","author":"admin","date":"May 7, 2026","format":false,"excerpt":"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 tutorial, you\u2019ll learn the basics of PHP, including statements, variables, operators,\u2026","rel":"","context":"In &quot;E-business &amp; E-marketing&quot;","block_context":{"text":"E-business &amp; E-marketing","link":"https:\/\/www.bricktowntom.com\/blog\/category\/ebusiness-emarketing"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604276php-introduction.jpg?fit=1200%2C680&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604276php-introduction.jpg?fit=1200%2C680&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604276php-introduction.jpg?fit=1200%2C680&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604276php-introduction.jpg?fit=1200%2C680&ssl=1&resize=700%2C400 2x, https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1643604276php-introduction.jpg?fit=1200%2C680&ssl=1&resize=1050%2C600 3x"},"classes":[]},{"id":92134,"url":"https:\/\/www.bricktowntom.com\/blog\/04\/the-best-website-builder-tools-platforms-for-your-idea.html","url_meta":{"origin":92153,"position":5},"title":"The Best Website Builder Tools &amp; Platforms for Your Idea","author":"admin","date":"April 15, 2026","format":false,"excerpt":"So you want to create an online business? Welcome to the club! The freedom of releasing your own content or products for anyone in the world to access is liberating. Your website could lead to fame and fortune \u2026 but where do you start? This article lists popular options for\u2026","rel":"","context":"In &quot;E-business &amp; E-marketing&quot;","block_context":{"text":"E-business &amp; E-marketing","link":"https:\/\/www.bricktowntom.com\/blog\/category\/ebusiness-emarketing"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1620180573website-tools.jpg?fit=600%2C340&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1620180573website-tools.jpg?fit=600%2C340&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.bricktowntom.com\/blog\/wp-content\/uploads\/2022\/02\/1620180573website-tools.jpg?fit=600%2C340&ssl=1&resize=525%2C300 1.5x"},"classes":[]}],"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.bricktowntom.com\/blog\/wp-json\/wp\/v2\/posts\/92153","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bricktowntom.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bricktowntom.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bricktowntom.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bricktowntom.com\/blog\/wp-json\/wp\/v2\/comments?post=92153"}],"version-history":[{"count":7,"href":"https:\/\/www.bricktowntom.com\/blog\/wp-json\/wp\/v2\/posts\/92153\/revisions"}],"predecessor-version":[{"id":92494,"href":"https:\/\/www.bricktowntom.com\/blog\/wp-json\/wp\/v2\/posts\/92153\/revisions\/92494"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bricktowntom.com\/blog\/wp-json\/wp\/v2\/media\/92154"}],"wp:attachment":[{"href":"https:\/\/www.bricktowntom.com\/blog\/wp-json\/wp\/v2\/media?parent=92153"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bricktowntom.com\/blog\/wp-json\/wp\/v2\/categories?post=92153"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bricktowntom.com\/blog\/wp-json\/wp\/v2\/tags?post=92153"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}