Exercises in Php/MySql
These notes are a review of some of the basic features of using PHP/MySql
We are going to use the username_mount database with the activities table in it.
My example will connect to the jamesbond_mount database.
In your webserver folder under your name copy the folder called exercise_revision from
student_shared. This folder contains another folder called includes and one called css. The css folder
contains styles.css to style our webpage.
Here’ s how you use PDO (PHP Data Object) to establish a connection to a MySQL server:
$pdo = new PDO('mysql:host=localhost;dbname=username_mount', 'username', 'password');
In any case, PDO has three arguments:
1. A string specifying the type of database (mysql: ), the hostname of the server (host=localhost;
), and the name of the database (dbname=username_mount ).
2. The MySQL username you want PHP to use.
3. The MySQL password for that username.
Open your text editor, Sublime text or textmate, and enter this code and save it in the includes folder
as connect.php. (Note: use your own username not jamesbond)
<?php
try
{
$pdo = new PDO('mysql:host=localhost;dbname=jamesbond_mount', 'jamesbond', 'pwd');
}
catch (PDOException $e)
{
echo 'Unable to connect to the database server.';
exit;
}
echo 'Database connection established.';
?>
check the connection by putting a url similar to this url into your browser.
http://php.mmc.school.nz/301/username/exercise_revision/includes/connect.php
We don’t want the text 'Database connection established.' appearing every time we connect to the
database. So delete echo 'Database connection established.'; from the connect.php code and save
it.
We have now established a connection to the database.
Copy the file loop.php to your exercise_revision folder. Open it in your text editor
At the top, above <!DOCTYPE html>, add in this php code block
<?php
//first connect to the database
require_once('includes/connect.php');
?>
loop.php now looks like this.
A nice feature of PDO, is that you can loop directly over a select query, without needing to store the
result first.
The code on line three, includes the database connection and the HTML contains a table, that'll be
used to display the results of a select query.
So, let's create that query, we'll create it on the line after including the database connection. We'll
save it as SQL. And, it will be select, activity, theme, description, from activities, and then we'll have a
little order clause to it, so order by theme.
Place this code after require_once('includes/connect.php');
$sql= "SELECT activity,theme,description FROM activities
ORDER BY theme";
And instead of submitting this query to the database and storing the result, we can get direct access
to each row, in a for each loop.
So let's create that for each loop. We need to go down into the HTML part of the page, create a new
line between the two rows (between </tr> and <tr>) and enter this code
<?php foreach ($pdo -> query($sql) as $row) { ?>
Also enter this code <?php } ?> after </tr> to end the for each loop.
Here we have a php block. In there we have a for each loop. We use the data base connection
($pdo) and the query method. Then we pass that query method, the SQL query (query($sql). Then
we can alias that to a variable. It doesn't matter what you call the variable, but row is an obvious
choice, because we're going to go through each row, one at a time.
We now have this code for our table
<table>
<tr>
<th> Theme </th>
<th> Activity </th>
<th>Description</th>
</tr>
<?php foreach ($pdo -> query($sql) as $row) { ?>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<?php } ?>
</table>
So, we've now got the for each loop. And each time this is run, it will generate an associative
array containing the value of each column, in the current row. So we can display them in the table
cells, using the column names, as the array keys. So let's remove the non-breaking spaces, .
Our loop code is now
<?php foreach ($pdo -> query($sql) as $row) { ?>
<tr>
<td><?php echo $row['theme']; ?></td>
<td><?php echo $row['activity']; ?></td>
<td><?php echo $row['description']; ?></td>
</tr>
<?php } ?>
So that's a quick and easy way to display the results of the select query, without having to save the
result first.
But it's important to note, that this works only with a for each loop, it won't work with any other type of
loop.
In all other situations, the query method, returns an object containing the complete result set, as we'll
see next.
Fetching a Result Set
PDO has four different methods for fetching results from a database query. We will look at two of
these. The one you're most likely to use is fetch, which gets the next row from a results set. FetchAll
gets all the results at once and stores them as a multi-dimensional array.
Open the file fetch.php in your text editor and save it into the exercise_revision folder in the web
server.
We need to execute the query and store the result set. So we can do that on the next line, under line
5, add this code
$result = $pdo -> query($sql);
This will create a variable called $result. And then we use the database connection, $pdo, and call
the query method. We pass the SQL statement, the query, and this then stores the entire result set in
$result.
To be able to display that, we can do that one row at a time using the fetch method in a while
loop. So, let's scroll down between the two table rows. </tr> and <tr>, and add a new line on line 23;
<?php while ($row = $result ->fetch()) { ?>
and in a line between </tr> and </table> put this to close the while loop
<?php } ?>
We're using the fetch method in its default style. This returns the current row as an indexed array and
as an associative array. So you’ve got the choice of using the column number, counting from zero, or
the column name to display the values. So, let's do that. In this first table cell we'll have a PHP
block and we'll use the first row so we're counting from zero. In the other two we will use the column
name to display the values.
<h1>PDO: Fetching the Next Row</h1>
<table>
<tr>
<th>Theme</th>
<th>Activity</th>
<th>Description</th>
</tr>
<?php while ($row = $result ->fetch()) { ?>
<tr>
<td><?php echo $row[0]; ?></td>
<td><?php echo $row['activity']; ?>;</td>
<td><?php echo $row['description']; ?></td>
</tr>
<?php } ?>
</table>
Using fetchAll
Save the file fetchall.php to the webserver and edit it with your text editor.
This contains exactly the same SQL statement, the select statement, and it also submits it using the
query method, and stores the value in Result.
The Fetch All method gets all of the results together and returns them as a multi-dimensional array.
So let's do that. We'll save it as $all. I will use the result object and the fetchAll method.
Put this code after $result = $pdo -> query($sql);
$all = $result -> fetchAll();
In the HTML body of the page there's a couple of pre tags, so between them if we have a PHP block
and use print_r, we can inspect the contents of that multidimensional array, $all.
To do this put this php block between the pre tags
<?php print_r($all); ?>
So we'll save that and then view the page in a browser. And here's that multidimensional array. The
top level array elements, they're the rows. And each of the sub-arrays.
Notice that it contains each value twice. First with the name, and the second time with the column
number. When using fetchAll you're unlikely to want both the associative array and the indexed
array. So let's go back to the editing program and see how we can alter that. Scroll back up to
fetchAll. We can pass fetchAll and argument. We can use a PDO fetch constant. So, it's all in
caps. PDO then two colons and then FETCH.
And if we use FETCH_ASSOC and save that, this will give us an associative array.
Change our fetchAll() to be fetchAll(PDO::FETCH_ASSOC)
So let's go back to the browser and reload that and now we've just got the names of the columns.
And the alternative to FETCH_ASSOC is FETCH_NUM, and no prizes for guessing what this does. It
returns them as numbers, the indexed array.
© Copyright 2026 Paperzz