<html>
<head>
  <meta content="text/html; charset=UTF-8"
 http-equiv="content-type">
  <meta name="Author" content="John Donaldson">
  <title>Director Movie Search</title>
</head>
<body>
<div class="example-contents">
<div class="phpcode"><code><span class="html"><span class="default">
<h1>Search the movie database</h1>
<?php
  // get the artist id and name
  $dname = $_GET["dname"];
  if($dname){
     $arr = explode('|',$dname);
     $cid =  $arr[0];
     if(sizeof($arr)>0){
        $aname = $arr[1];
     }
   }
  ini_set('display_errors', 'On');
  error_reporting(E_ALL);

   //Make a connection to the mysql server
   $mysqli = new mysqli("sql.cs.oberlin.edu","alice","tiger","imdb");

   if($mysqli->connect_errno){
     echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
   }

   $mysqli->set_charset('utf8mb4');
?>
<form method="get" action="example6.php">
  Enter an director name to search for:
  <input type="text" size="40" name="dname">
  <input type="submit">
  </form>
<?php
//Execute this section if a director name has been entered
if($dname){
  $query = "SELECT tcode,title,genre,year FROM persons natural join directed natural join productions natural join genres where type='movie' and year is not null and name= ? order by genre,year,title limit 500";
  $stmt = $mysqli->prepare($query);
  if(!$stmt){
    print("Prepare failed (" . $mysqli->error . ")" );
  }

  if (!$stmt->bind_param("s", $dname)) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
  }

  $stmt->execute();

  $res = $stmt->get_result();

  if($res->num_rows == 0){
    print 'No films found for director '.$dname;
  }
  else {
    print "<h2>Films of $dname:</h2>";
  }

  // Print the query results as a bulleted list, grouped by genre
  $current_genre = '';
  print '<ul>';
  $first = TRUE;
  while ($row = $res->fetch_assoc()) {
    if($row['genre'] != $current_genre){
      // change genre
      if($first)
        $first = FALSE;
      else
        print '</ul>';  // end of previous genre
      $current_genre = $row['genre'];
      print '<li>' . $current_genre . '</li>';
      print '<ul>';  // start a new genre list
    }
    print '<li>' . $row['title'] . ' (' . $row['year'] . ')</li>';
  }  // end of while
  print '</ul></ul>';
}  // end of if $dname
?>
</span><span class="default"></span></span>
</code></div>
</div>
</body>
</html>
