PHP

Exercises

PHP Exercises

1. Hello World

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

Or even:

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

2. Variables

<?php
  $num1 = 10;
  $num2 = 15;
?>

3. Arrays

<?php
  $names = array('John', 'Mary', 'Jane');
?>

4. More Arrays

* Create a new file called **exercise4.php**.
* Inside that file insert the following code:
  <?php
    $people = array(
      array('name' => 'John', 'job' => 'Builder'),
      array('name' => 'Mary', 'job' => 'Astronaut'),
      array('name' => 'Jane', 'job' => 'Nurse'),      
    );
  ?>
* Add some code to the script so that the output is the following:
Jon is a Builder
Mary is a Astronaut
Jane is a Nurse
* Don't forget to add a line break between them (think in HTML).
* Verify if your script works by navigating to http://gnomo.fe.up.pt/~upxxxxxx/exercise4.php

5. HTML

Name Job
John Builder
Mary Astronaut
Jane Nurse

<tr><td><a href="hello.php">John</a></td><td>Builder</td></tr>
<tr><td><a href="hello.php?name=John">John</a></td><td>Builder</td></tr>
  <p>Hello John!</p>
  <a href="list.php">Go back</a>

7. Forms

8. Database

<?php
  $dbh = new PDO('pgsql:host=dbm.fe.up.pt;port=5432;dbname=USERNAME', 'USERNAME', 'PASSWORD');
  $dbh->query('SET SCHEMA employees');
?>
$stmt = $dbh->prepare('SELECT * FROM employee');
$stmt->execute();
$employees = $stmt->fetchAll();
~~~list

  * You can try using **print_r** to print the *employees* array to check if the query has been successful.

~~~php
print_r($employees);

9. Wrapping it Up