A Simple Example

Let's dive right in and look at a very simple example which calls some data and displays it within your web browser.

Our first example is just to get us off the ground and we will only be using a simple query that does not accept any untrusted query parameters from the user.

NOTE: This isn't a complete example. It does not handle errors, which is bad practice and can lead to security vulnerabilities. We'll cover that more in later sections. Our goal here is to get a simple example off the ground and we'll build on this as we go.

This code should be put into index.php in your webroot directory.

<?php
// make a connection to the MySQL server
$db = new PDO("mysql:host=localhost;dbname=employees;", "[username]", "[password]");

// prepare a query
$prep = $db->prepare("select lastName, firstName from names");

// execute the query
$prep->execute();

// fetch the results and put them into a variable
$results = $prep->fetchAll();

// echo the results to the browser
echo "<pre>";
print_r($results);
echo "</pre>";

Within this code, you'll need to replace [username] and [password] with your actual database credentials that you've previously created for this project.

After running this code, you should see output that is similar to the following:

Array
(
    [0] => Array
        (
            [id] => 1
            [0] => 1
            [started] => 2019-01-01 00:00:00
            [1] => 2019-01-01 00:00:00
            [lastName] => Smith
            [2] => Smith
            [firstName] => Jim
            [3] => Jim
            [salary] => 120000.01
            [4] => 120000.01
        )
etc...

This is a raw dump of the data from the database. As you can see, we have our first working PHP / MySQL program!