2016-12-08 17 views
1

我有一個php文件,它在php輸出中轉換我的sql查詢。一切正常。但現在我需要一個輸出作爲txt.file和我的代碼不起作用。作爲txt.file的SQL結果由php

這裏查詢:

<?php 
$pdo = new PDO('mysql:host=localhost;dbname=DB', 'USER', 'PW'); 

$result = ("SELECT o.order_id AS Bestellnummer, o.customer_id AS Kundennummer, o.order_status_id AS Bestellstatus, op.quantity AS Anzahl, op.model AS Pharmacode, op.name AS Bezeichnung, p.location AS Lieferant, o.shipping_company AS Firma, o.shipping_firstname AS Vorname, o.shipping_lastname AS Nachname, o.shipping_address_1 AS Lieferadresse, o.shipping_postcode AS PLZ, o.shipping_city AS Ort 
FROM oc_order o 
INNER JOIN oc_order_product op 
ON o.order_id = op.order_id 
INNER JOIN oc_product p 
ON op.product_id = p.product_id 
WHERE o.order_status_id = 1 AND p.location = 1 
ORDER BY o.order_id, op.model"); 



echo "<table border='0'> 
<tr> 
<th>Best.Nr</th> 
<th>Kd.Nr</th> 
<th>Status</th> 
<th>Anz.</th> 
<th>Pharmacode</th> 
<th>Bezeichnung</th> 
<th>Lieferant</th> 
<th>Firma</th> 
<th>Vorname</th> 
<th>Nachname</th> 
<th>Adresse</th> 
<th>PLZ</th> 
<th>Ort</th> 
</tr>"; 

foreach ($pdo->query($result) as $row) { 

    echo "<tr>"; 
    echo "<td>" . $row['Bestellnummer'] . "</td>"; 
    echo "<td>" . $row['Kundennummer'] . "</td>"; 
    echo "<td>" . $row['Bestellstatus'] . "</td>"; 
    echo "<td>" . $row['Anzahl'] . "</td>"; 
    echo "<td>" . $row['Pharmacode'] . "</td>"; 
    echo "<td>" . $row['Bezeichnung'] . "</td>"; 
    echo "<td>" . $row['Lieferant'] . "</td>"; 
    echo "<td>" . $row['Firma'] . "</td>"; 
    echo "<td>" . $row['Vorname'] . "</td>"; 
    echo "<td>" . $row['Nachname'] . "</td>"; 
    echo "<td>" . $row['Adresse'] . "</td>"; 
    echo "<td>" . $row['PLZ'] . "</td>"; 
    echo "<td>" . $row['Ort'] . "</td>"; 
    echo "</tr>"; 
    } 
echo "</table>"; 


mysql_close($con); 
?> 

我需要爲TXT或CSV一個輸出endcode。我想初始代碼(SELECT ...)沒有清晰的輸出字符串來連接輸出的新代碼。

+0

最後的代碼是正確的,唯一的區別使用'mysql_ *'函數代替'PDO',這會在PHP 7中造成問題。 –

+0

不推薦使用'mysql'擴展名。開始使用'mysqli'或'PDO'來避免像SQL注入這樣的漏洞攻擊。 – Perumal

+0

@JiriHrazdil'mysql'擴展不僅在PHP 7中引起問題,它從PHP 5.5.0開始已被棄用。 5.5.0之後的版本都會使用'mysql'造成問題。 – Perumal

回答

0

您可以嘗試用PHP,比把它放到文件收集完整的字符串: 所以你需要循環之前創建$string變量和追加每行$string

$string = ""; 
$file_path = "file.csv"; 
foreach ($pdo->query($result) as $row) { 
    $string .= $row['Bestellnummer'] . ','; 
    ... 
} 
file_put_contents($file_path, $string) 
+0

我試過但沒有積極效果:file_put_contents(「test.txt」,$ output);需要$ query = $ this-> db - > $ query(「output」);這不適用於我的主要代碼。 – 27eleven

+0

顯示您的代碼,請 –

+0

嗨,這是不可能回答整個代碼,所以我已經在最初的問題中公佈了整個代碼。 – 27eleven