PHP

Exercises

PHP Exercises

1. First PHP script

<?php echo "<h1>Hello World!</h1>"?>
<h1>
<?php echo "Hello World!" ?>
</h1>

Or even:

<h1><?= "Hello World!" ?></h1>

2. HTTP Parameters

3. SQLite Database creation

ssh upxxxxxx@gnomo.fe.up.pt
cd public_html
mkdir exercise3
cd exercise3
wget http://paginas.fe.up.pt/~arestivo/page/files/exercises/php/news.sql
sqlite3 -init news.sql news.db
select * from news where id = 4;
select * from comments where news_id = 4;
.exit
ls
sqlite3 news.db

4. Listing data from SQLite

<?php
  $db = new PDO('sqlite:news.db');
?>
  $stmt = $db->prepare('SELECT * FROM news');
  $stmt->execute();
  $articles = $stmt->fetchAll();
  foreach( $articles as $article) {
    echo '<h1>' . $article['title'] . '</h1>';
    echo '<p>' . $article['introduction'] . '</p>';
  }

5. Complete Page

SELECT news.*, users.*, COUNT(comments.id) AS comments
FROM news JOIN
     users USING (username) LEFT JOIN
     comments ON comments.news_id = news.id
GROUP BY news.id, users.username
ORDER BY published DESC
  $stmt = $db->prepare('SELECT * FROM news JOIN users USING (username) WHERE id = :id');
  $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
  $stmt->execute();
  $article = $stmt->fetch();

or:

  $stmt = $db->prepare('SELECT * FROM news JOIN users USING (username) WHERE id = ?');
  $stmt->execute(array($_GET['id']));
  $article = $stmt->fetch();
  $stmt = $db->prepare('SELECT * FROM comments JOIN users USING (username) WHERE news_id = ?');
  $stmt->execute(array($_GET['id']));
  $comments = $stmt->fetchAll();

6. Data layer separation

<?php
  include_once('database/connection.php');
  include_once('database/news.php');
  $articles = getAllNews();
?>

7. Presentation layer separation

<?php
  include_once('database/connection.php'); // connects to the database
  include_once('database/news.php');       // loads the functions responsible
                                           // for the news table
  $articles = getAllNews();                // gets all news from the database

  include('templates/common/header.php');  // prints the initial part of the HTML document
  include('templates/news/list_news.php'); // prints the list of news in HTML
  include('templates/common/footer.php');  // prints the initial part of the HTML document
?>

8. Editing data

9. Authentication

<?php
  session_start();                         // starts the session
  include_once('database/connection.php'); // connects to the database
  include_once('database/users.php');      // loads the functions responsible for the users table

  if (userExists($_POST['username'], $_POST['password']))  // test if user exists
    $_SESSION['username'] = $_POST['username'];            // store the username

  header('Location: ' . $_SERVER['HTTP_REFERER']);
?>

10. Insert and delete

Solutions

Solutions for these PHP exercises.