2017-09-27 148 views
0

我一直在建立數據庫來計算終止費用。將MYSQL結果導出爲CSV

下面的代碼(termination.php)從前一頁上的複選框中選取多行,處理查詢並將其輸出到一個簡單的HTML表中。這是按要求工作的。

<?php 
require_once '.\Includes\dbcon.php'; 

$rowCount = count($_POST["select"]); 

for ($i = 0; $i < $rowCount; $i++) 
    { 
    $sql = "UPDATE `{$_POST['customer']}` SET `DateOfCancellation`='{$_POST['dateofcancellation']} WHERE ServiceID={$_POST['select'][$i]}'"; 
    if ($con->query($sql) === TRUE) 
     { 
     echo ""; 
     } 
     else 
     { 
     echo "Error: " . $sql . "<br />" . $con->error; 
     } 
    } 

?> 
<a href = ".\index.php">Back to Index</a></p> 
<strong>Termination for <?php echo ucwords($_POST['customer']) ?> Based on Cancellation Date <?php echo $_POST['dateofcancellation'] ?></strong></p> 
<table> 
    <tr> 
     <th>Service Name</th> 
     <th>License Start Date</th> 
     <th>License End Date</th> 
     <th>Cost Per Calendar Month</th> 
     <th>Balance on Termination</th> 
<?php 
$rowCount = count($_POST["select"]); 

for ($i = 0; $i < $rowCount; $i++) 
    { 
    $sql = mysqli_query($con, "$select FROM `{$_POST['customer']}` WHERE ServiceID={$_POST['select'][$i]}"); 
    $row[$i] = mysqli_fetch_array($sql); ?> 
<tr> 
<td><?php 
    echo $row[$i]['ServiceName']; ?></td> 
<td><?php 
    echo $row[$i]['LicenseStart']; ?></td> 
<td><?php 
    echo $row[$i]['LicenseEND']; ?></td> 
<td>£<?php 
    echo $row[$i]['CostPCM']; ?></td> 
<td>£<?php 
    echo $row[$i]['CostOfTermination']; ?></td> 
<?php 
    } 

$sql = "UPDATE `{$_POST['customer']}` SET `DateOfCancellation`='0000-00-00'"; 

if ($con->query($sql) === TRUE) 
    { 
    echo ""; 
    } 
    else 
    { 
    echo "Error: " . $sql . "<br />" . $con->error; 
    } 

$sum = 0; 

for ($i = 0; $i < $rowCount; $i++) 
    { 
    $sum = $sum + $row[$i]['CostOfTermination']; 
    } 

echo "<strong>The Total Balance of Termination is: </strong>£" . $sum; 
echo "<p>"; 
$sum = 0; 

for ($i = 0; $i < $rowCount; $i++) 
    { 
    $sum = $sum + $row[$i]['CostPCM']; 
    } 

echo "<strong>Balance of Termination per Month: </strong>£" . $sum; 
echo "<p>"; 
?> 
</tr> 

我需要做什麼才能將表中的數據導出到Excel文件(理想情況下)或CSV文件中。我已經嘗試了幾種不同的方法,可以獲取標題但不是實際的數據。我認爲for循環是什麼讓我失望。

+0

這是最好的發佈您的代碼到實際的問題。外部鏈接變壞。 –

+0

我建議編輯您的答案,包括您在外部來源鏈接的代碼。隨時只保留最相關的部分 – mabe02

+0

接受。謝謝你的建議! –

回答

0

嘗試這樣:

<?php 

$titles = "Service Name,License Start Date,License End Date,Cost Per Calendar Month,Balance on Termination"; 

$rowCount = count($_POST["select"]); 
echo $titles; 

for ($i = 0; $i < $rowCount; $i++) 
    { 
    $sql = mysqli_query($con, "$select FROM `{$_POST['customer']}` WHERE ServiceID={$_POST['select'][$i]}"); 

    $row[$i] = mysqli_fetch_array($sql); 

    echo 
    $row[$i]['ServiceName'] . "," . 
    $row[$i]['LicenseStart'] . "," . 
    $row[$i]['LicenseEND'] . "," . 
    $row[$i]['CostPCM']  . "," . 
    $row[$i]['CostOfTermination'] ."<br>"; 

}