1 PHP libraries, extensions

If you are contemplating writing code for a commonly used task (search engine, guestbook, shopping cart), it is probably a good idea to check whether such code already exists. For PHP there are three good places to look: The command-line installer for Pear and Pecl is called pear. This is the preferred way of installing PHP extensions.

1.2 Exercises

1) Have a look at the websites above.

2 Databases

PHP can be used with different database management systems, but most commonly is used with MySQL.

Database interfaces support the following tasks:

  • connect to the database,
  • prepare a query (as a string),
  • execute the query,
  • fetch the results (either row by row or as an array)
  • finish the query (so that the database can clean up its buffers, this is optional)
  • disconnect from the database

    Below is an example for accessing a Mysql database from PHP.

    2.1 Mysql

    <html><head><title>Example</title>
    </head><body>

    <?php

    // Connection and select database
    $link = mysql_connect('mysqlhost3.napier.ac.uk','username', 'password')
    or die('Could not connect: ' . mysql_error());
    mysql_select_db('test') or die( "Unable to select database");

    // Performing SQL query
    $query = "select * from test";
    $result = mysql_query($query) or die('Query failed: ' . mysql_error());
    $num = mysql_numrows($result);

    if ($num == 0) {
       echo "No results where returned<p>";
    } else {
       echo "<table>\n";
       while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
         echo "<tr>\n";
    // you can either use a foreach statement:
    //    foreach ($line as $col_value) {
    //      echo "<td>$col_value</td>";
    //    }
    // or you can use it like this:
        echo "<td>",$line['firstfield'],"</td>";
        echo "<td>",$line['secondfield'],"</td>";
        echo "<td>",$line['thirdfield'],"</td>";
        echo "</tr>\n";
      }
      echo "</table>\n";
    }

    mysql_free_result($result);
    mysql_close($link);
    ?>

    </body></html>

    2.1 Exercises

    2) Try to get the MySQL example to work on your database. You will need the hostname, username, and password that you were given by C&IT.