title: Export database to different sheets within excel file in php
body: <p>I want to export contacts from database into one excel file, so that each category is a separate sheet. I've been looking at this [example][1], and it works fine, except the fact I don't know how to manage sheets. This puts all my data into one sheet.</p>
  
  <p>This is my code:</p>
  
  <pre><code>&lt;?php
    $xls_filename = 'export_'.date('Y-m-d').'.xls'; // Define Excel (.xls) file name
  
    header("Content-Type: application/xls");
    header("Content-Disposition: attachment; filename=$xls_filename");
    header("Pragma: no-cache");
    header("Expires: 0");
  
    include_once "connect.php";
    $sep = "\t"; // tabbed character
    $query1 = "select * from category";
    $result1 = mysqli_query($conn, $query1);
    if (!$result) {
      echo "Error: " . $sql . "&lt;br&gt;" . mysqli_error($conn);
      $check = false;
    }
    else {
      while($category = mysqli_fetch_object($result1)) {
        $query2 = "select * from contact inner join contact_category on contact.email = contact_category.contact_email
           where contact_category.category_id ='$category-&gt;id'";
        $result2 = mysqli_query($conn, $query2);
        if (!$result2) {
          echo "Error: " . $sql . "&lt;br&gt;" . mysqli_error($conn);
          $check = false;
        }
        else {
          echo $category-&gt;name;
          //$category_name should be my new sheet's name
          $schema_insert .= "First name".$sep;
          $schema_insert .= "Last name".$sep;
          $schema_insert .= "\n";
          while($contact= mysqli_fetch_object($result2)) {
            $schema_insert .= $contact-&gt;first_name.$sep;
            $schema_insert .= $contact-&gt;last_name.$sep;
            $schema_insert .= ""."\n";
          }
        }
      }
      print(trim($schema_insert));
      print "\n";
    }
  ?&gt;
  </code></pre>