为什么它只返回一行?

时间:2013-07-10 16:07:14

标签: php html mysql excel

我使用以下代码将数据库表导出为ex​​cel。此代码的问题是它只返回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>');
 ?>

我是新手。请帮帮我..

1 个答案:

答案 0 :(得分:1)

您的代码有多处问题。

1)您没有生成Excel文件。你正在生成一些Excel,它恰好可以伪装成Excel文件。

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

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

<caption>必须位于<td>内,或完全位于表格的外部。

3)你容易受到SQL injection attacks的攻击。请勿在生产环境中使用此代码。你只会破坏服务器。

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