Monday 25 April 2022

Export mysqli resultset as excel with nested table in PhP

 <?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$con = mysqli_connect("localhost", "root", "", "tablename");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$output = '';
$stmt3 = $con->prepare("SELECT id,registrationid,name,email,mobile,nationality,state,district,gender from adv33");
$stmt3->execute();
$stmt3->bind_result($id, $registrationid, $name, $email, $mobile, $nationality, $state, $district, $gender);
$stmt3->store_result();
if ($stmt3->num_rows > 0) {
    $output .= '
    <table border="1">
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Mobile</th>                      
                        <th>Nationality</th>
                        <th>State</th>
                        <th>District</th>
                        <th>Gender</th>                                            
                    </tr>
  ';
    while ($stmt3->fetch()) {
        $output .= '
                    <tr>                         
                         <td>' . $name . '</td>
                         <td>' . $email . '</td>
                         <td>' . $mobile . '</td>                         
                         <td>' . $nationality . '</td>
                         <td>' . $state . '</td>
                         <td>' . $district . '</td>
                         <td>' . $gender . '</td>                         
                    </tr>';
        $output .= '                  
         <table border="1">
         <tr>
         <td><b>Post</b></td>
         <td><b>Company</b></td>         
           <td><b>From Date</b></td>
            <td><b>To Date</b></td>
            <td><b>Scale of Pay</b></td>          
   ';
        $stmt4 = $con->prepare("SELECT slno,email,post,company,fromdate,todate,scale FROM adv33exp  where email ='$registrationid'");
        $stmt4->execute();
        /* bind result variables */
        $stmt4->bind_result($slno, $email, $post, $company, $fromdate, $todate, $scale);
        $stmt4->store_result();
        if ($stmt4->num_rows > 0) {
            /* fetch value */
            while ($stmt4->fetch()) {
                $output .= '
                     <tr>
                         <td>' . $post . '</td>
                         <td>' . $company . '</td>                        
                         <td>' . $fromdate . '</td>
                         <td>' . $todate . '</td>
                         <td>' . $scale . '</td>                         
                    </tr>
                ';
            }
        }
    }
    $output .= '</table>';
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=Applicants.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    echo $output;
}
?>

No comments:

Post a Comment