JSON from PHP data

<?php

// Connecting, selecting database
  $mysqli = new mysqli('localhost','class','cscie12','coursecatalog');
  if ($mysqli->connect_errno) {
      echo "Failed to connect to mysql: ".$mysqli->connect_errno." ".$mysqli->connect_error;
  }
$dept_code = $_GET['department_code'];
$sqlescaped_dept_code = $mysqli->real_escape_string($dept_code);

// Performing SQL query
$query = 'SELECT course_group_long, num_int, num_char, term, title, description, faculty_text';
$query .= ' from courses where department_code = ';
$query .= "'".$sqlescaped_dept_code."'";
$query .= ' order by course_group_long, num_int, num_char, title';

$result = $mysqli->query($query);

$i = 0;
while ($row = $result->fetch_assoc()) {
  $results[$i++] = $row;
}

$template_data['courses'] = $results;
$template_data['department_name'] = $dept_code;

header('Content-type: application/json');
echo json_encode($template_data);

// free and close
$result->free();
$mysqli->close();
?>