Journal Articles

CVu Journal Vol 27, #1 - March 2015 + Programming Topics
Browse in : All > Journals > CVu > 271 (11)
All > Topics > Programming (877)
Any of these categories - All of these categories

Note: when you create a new publication type, the articles module will automatically use the templates user-display-[publicationtype].xt and user-summary-[publicationtype].xt. If those templates do not exist when you try to preview or display a new article, you'll get this warning :-) Please place your own templates in themes/yourtheme/modules/articles . The templates will get the extension .xt there.

Title: LAMP on Ubuntu

Author: Martin Moene

Date: 08 March 2015 20:58:50 +00:00 or Sun, 08 March 2015 20:58:50 +00:00

Summary: Ian Bruntlett shares his notes on setting up a basic web application.

Body: 

Sometime in 2014 I started working my way through an Internet programming book – Learning PHP, MySQL, JavaScript, CSS & HTML5 (LPMJ). Whilst it is a good guide, I had to research certain system administration details myself. This document was written using my personal notes, text books and a computer with a fresh install of Ubuntu 14.10. As approved of by that book, I have reused some of their examples. Please note this is a study exercise – commercial websites are likely to do things differently for scalability and security.

First my personal preferences. I installed Synaptic Package Manager because I like its front end – it helps me explore the packages available. I also installed ttf-mscorefonts-installer which in turn installs some free fonts from Microsoft – in particular it provides me with Times New Roman and Comic Sans MS. I also installed an editor – emacs – because I like it :)

Packages to install..

Here are the actual names of the packages involved:

Setting files up

Start up a terminal window/shell window. When you are typing these commands, replace ian with your username. Type in this command:

  sudo chown ian:ian /var/www/html

The directory /var/www/html is used by Apache to find its HTML files. This command changes the owner and group ID of that folder so that you can put your HTML files there. There is an index.html file, owned by root, already in that directory. To view it, start a web-browser and type in an address of localhost. You should see the Apache2 Ubuntu Default Page. As we are going to modify that file for our own purposes, do this:

  cd /var/www/html
  mv index.html index_original.html

From now on I am going to refer to var/www/html as ‘HTML Home’.

Our first webpage

Still in HTML Home, start a text file and type in Listing 1, saving it as index.html.

<!DOCTYPE html>
<html>
  <head>
    <title>Ian's LAMP index.html</title>
    <meta http-equiv="Content-Type" 
          content="text/html;charset=utf-8">
  </head>
  <body>
    <h2>Ian's LAMP files test area</h2>
    <ul>
      <li><a href="http://validator.w3.org/">
         Site to validate HTML5 files.</a></li>
    </ul>
  </body>
</html>
			
Listing 1

You can then check the integrity of the HTML script by clicking on the ‘Site to validate etc’ link, select ‘Validate by File Upload’ and use the ‘Browse’ button to get to /var/www/html/index.html

Configuring Apache for ease of development.

Apache – displaying errors present in PHP.

To display syntax errors, assign rights to edit /etc/php/apache2/php.ini and in that file, set these settings on: display_errors, display_startup_errors.

They are very useful. After changing these settings either send the Apache process a SIGHUP or reboot your computer.

When you want to use your development computer as a webserver (not always the best idea), set these (display_errors, display_startup_errors) settings to Off.

Our first piece of PHP5

Insert this line into index.html:

  <li><a href="http://localhost/blank.php">An
  almost blank PHP file.</a></li>

And put the HTML file in Listing 2 in HTML Home, named blank.php.

<!DOCTYPE html>
<html>
  <head>
    <title>Ian's LAMP experiments</title>
    <meta http-equiv="Content-Type"
          content="text/html;charset=utf-8">
  </head>
  <body>
    <h2>Ian's LAMP <?php echo __FILE__ ?> for CVu
    magazine </h2>
    <p>
      <?php
        echo "blank";
      ?>
    </p>
  </body>
</html>
			
Listing 2

Save it, press F5 and click on ‘An almost blank etc’ file. In the <h2> tag pair, you should notice there is a bit of PHP there. Congratulations, you have created and run your first PHP programme.

Our system has been set up to have a webserver (Apache), a scripting language (PHP5) and a database server (MySQL).

Creating a database

Go to a command prompt and type in “mysql -u root -p” and type in your MySQL root password. This gets you to the MySQL command prompt.

  ian@turing:/var/www/html$ mysql -u root -p
  Enter password:
  Welcome to the MySQL monitor.  Commands end with
  ; or \g.
  (some redundant details removed).
  Type 'help;' or '\h' for help. Type '\c' to clear
  the current input statement.
  mysql> 

Before we can store any information, we need to set up a database. Type in these commands:

  create database publications;
  use publications;

And you should see:

  mysql> create database publications;
  Query OK, 1 row affected (0.00 sec)
  mysql> use publications;
  Database changed
  mysql>

Creating a database table

Also at the MySQL prompt, type:

  drop table classics;
  CREATE TABLE classics (
   author   VARCHAR(128),
   title    VARCHAR(128),
   category VARCHAR(16),
   year     SMALLINT,
   isbn     CHAR(13),
   INDEX(author(20)),
   INDEX(title(20)),
   INDEX(category(4)),
   INDEX(year),
   PRIMARY KEY (isbn)
  ) ENGINE MyISAM;

Populating a database table

Here are some SQL statements to populate the above classics table:

  INSERT INTO classics (author, title, category,
  year, isbn )
  VALUES('Mark Twain','The adventures of Tom
  Sawyer','Fiction', 1876,'9781598184891');

And to verify that those statements worked, type this into a MySQL prompt:

  select * from classics order by author;

You should get the result shown in Figure 1.

+---------------------+------------------------------+-------------+------+---------------+
| author              | title                        | category    | year | isbn          |
+---------------------+------------------------------+-------------+------+---------------+
| Mark Twain          | The adventures of Tom Sawyer | Fiction     | 1876 | 9781598184891 |
+---------------------+------------------------------+-------------+------+---------------+
1 row in set (0.00 sec)
			
Figure 1

Accessing a database on a web page

First you need to have database login details. In the LPMJ book, a file called login.php is used. Type Listing 3 into /var/www/html/login.php :

<?php // login.php
  $db_hostname = 'localhost';
  $db_database = 'publications';
  $db_username = 'root';
  $db_password = 'Your Password Here';
?>
			
Listing 3

Then you need a programme to access the database in HTML Home. Something like /var/www/html/db_experiment.php (Listing 4).

<!DOCTYPE html>
<html>
  <head>
    <title>Ian's LAMP and PHP experiments</title>
    <meta http-equiv="Content-Type"
          content="text/html;charset=utf-8">
  </head>
  <body>
    <h2>Ian's LAMP <?php echo __FILE__ ?> from
      Chapter 10 Accessing MySQL Using PHP</h2>
    <p>
    Doing database stuff
<?php
  function connect_to_db($host,$user,$passwd)
  {
    echo "<br>Hi from connect_to_db()<br>";
    echo "<br>login details : Username $user,
    Hostname $host<br>";
    $db_server = mysql_connect($host, $user,
      $passwd);
    print "<br>db_server = $db_server<br>";
    if (!$db_server) die("Unable to connect to
      MySQL: " . mysql_error() );
    else echo "Connected to server<br>";
    mysql_select_db("publications")
    or die ("Unable to select database: " 
     . mysql_error() );
    echo "Database selected<br>";  
    return $db_server;
  }
  function one_at_a_time_results($result)
  {
     echo "Hi from one_at_a_time_results $result
       <br>";
     $rows = mysql_num_rows($result);
     for ( $j=0; $j<$rows; ++$j)
     {
       echo 'Author: '   . mysql_result
         ($result, $j, 'author') . '<br>';
       echo 'Title: '    . mysql_result
         ($result, $j, 'title') . '<br>';
       echo 'Category: ' . mysql_result
         ($result, $j, 'category') . '<br>';
       echo 'Year: '     . mysql_result
         ($result, $j, 'year') . '<br>';
       echo 'ISBN: '     . mysql_result
         ($result, $j, 'ISBN') . '<br><br>';
      }
  }
  function row_at_a_time_results($result)
  {
    echo "Hi from row_at_a_time_results $result
      <br>";
    $num_rows = mysql_num_rows($result);
    for ( $j=0; $j<$num_rows; ++$j)
    {
      $row = mysql_fetch_row($result);
      echo 'Author: '   . $row[0] . '<br>';
      echo 'Title: '    . $row[1] . '<br>';
      echo 'Category: ' . $row[2] . '<br>';
      echo 'Year: '     . $row[3] . '<br>';
      echo 'ISBN: '     . $row[4] . '<br><br>';
    }
  }
  require_once 'login.php';
  $db_server=connect_to_db($db_hostname,
    $db_username,$db_password);
  $query = "SELECT * FROM classics";
  $result = mysql_query($query);
  if (!$result) die ("Database access failed: " 
    . mysql_error() );
  echo "Query $query succeeded<br><br>";
  //one_at_a_time_results($result);
  row_at_a_time_results($result);
  mysql_close($db_server);
?>
    </p>
  </body>
</html>
			
Listing 4

Once that programme is stored, it can be run from within a web browser. Start a browser and type in this address: http://localhost/db_experiment.php

You should see something like Figure 2.

Ian's LAMP /var/www/html/db_experiment.php from Chapter 10 Accessing MySQL Using PHP

Doing database stuff
Hi from connect_to_db()

login details : Username root, Hostname localhost

db_server = Resource id #2
Connected to server
Database selected
Query SELECT * FROM classics succeeded

Hi from row_at_a_time_results Resource id #3
Author: Mark Twain
Title: The adventures of Tom Sawyer
Category: Fiction
Year: 1876
ISBN: 9781598184891
			
Figure 2

And that’s it!

Notes: 

More fields may be available via dynamicdata ..