-3

我正在使用以下代码将数据库表导出到 excel。这段代码的问题是它在 Excel 中只返回一行。我不知道代码有什么问题。mysql代码或php代码。我一直在尝试更正代码。但我还做不到。所以我真的需要你的帮助。这是代码。

 <?php

$dbHost = 'localhost';          //  database host
$dbUser = 'root';       //  database user
$dbPass = 'passwrd';        //  database password
$dbName = 'mydatabase';         //  database name
$dbTable = 'table';         // table name

 $connection = @mysql_connect($dbHost, $dbUser, $dbPass) or die("Couldn't connect.");
 $db = mysql_select_db($dbName, $connection) or die("Couldn't select database.");

 $f=$_GET['fdate'];
 $t=$_GET['tdate'];
 $y=$_GET['Year'];

 $sql = "SELECT regd, Roll_no, Name_of_Student,
 SUM( IF( `Subject` = 'ENG-I', Mark_score, 0 ) ) AS Eng_I,
 SUM( IF( `Subject` = 'ENG-II', Mark_score, 0 ) ) AS Eng_II,
 SUM( IF( `Subject` = 'Mizo', Mark_score, 0 ) ) AS Mizo, 
 SUM( IF( `Subject` = 'Hindi', Mark_score, 0 ) ) AS Hindi,
 SUM( IF( `Subject` = 'EVS', Mark_score, 0 ) ) AS EVS,
 SUM( IF( `Subject` = 'Mathematics', Mark_score, 0 ) ) AS Maths,
 SUM( IF( `Subject` = 'GK', Mark_score, 0 ) ) AS GK,
 Sum(Full_mark) as Fullmark, Sum(Mark_score) as Totalscore, 
 Sum(Mark_score)/sum(Full_mark)*100 as Percentage FROM $dbTable
 WHERE Test_date Between '$f' and '$t' and Year='$y' and Class='IV' GROUP BY Subject && regd Order by Totalscore Desc";
 $result = @mysql_query($sql)   or die("Couldn't execute query:<br>".mysql_error().'<br>'.mysql_errno());

header('Content-Type: application/vnd.ms-excel');   
header('Content-Disposition: attachment; filename=Class-IV-'.date('d-M-Y').'.xls');
header('Pragma: no-cache');
header('Expires: 0');

echo '<table border="1"><caption><b>AR ELLS SCHOOL<br >CHALTLANG : MIZORAM<br />WEEKLY TEST BETWEEN '.$f.' AND '.$t.'&nbsp; <br /> CLASS : IV</b></caption><tr bgcolor="silver">';
for ($i = 0; $i < mysql_num_fields($result); $i++)   
    echo '<th>'.mysql_field_name($result, $i).'</th>';
print('</tr>');

while($row = mysql_fetch_row($result))
{
    //set_time_limit(60); 
    $output = '<tr style="background-color:white">';
    for($j=0; $j<mysql_num_fields($result); $j++)
    {
        if(!isset($row[$j]))
            $output .= '<td>&nbsp;</td>';
        else
            $output .= "<td>$row[$j]</td>";
    }
    print(trim($output))."</tr>\t\n";
}
echo('</table>');
 ?>

我是新手。请帮我..

4

1 回答 1

1

您的代码有多个问题。

1)您没有生成 Excel 文件。您正在生成一些 HTML,Excel 恰好能够假装它确实是一个 Excel 文件。

2) 您生成的 HTML 无效且损坏。你不能把<caption>你放在哪里。HTML 表格必须看起来像

<table>
<tr>
   <td>...</td>
</tr>
</table>

<caption>必须要么在表内<td>,要么完全在表外。

3) 您容易受到SQL 注入攻击。不要在生产环境中使用此代码。你只会让你的服务器被摧毁。

4)你自己做过任何调试吗?例如捕获生成的查询并在外部工具中自己运行它?它在那里返回多行吗?如果不是,那么是您的查询损坏了,而不是 PHP 代码。

于 2013-07-10T16:20:53.357 回答