2011-06-08 74 views
-1

我正在跨越一個錯誤來試圖將數據從MySQL使用PHP錯誤出口MYSQL數據爲PDF文件,PHP腳本

這裏是我的PHP代碼導出爲PDF:

<?php 

require('fpdf.php'); 
include ('connection.php'); 

$data = mysql_query("SELECT * FROM sold WHERE imei = '87712839712893'"); 
$result = mysql_fetch_array($data); 

$saledate = $result['saledate']; 
$price = $result['sellingprice']; 

$pdf=new FPDF(); 
$pdf->AddPage(); 
$pdf->SetFont('arial','B',10); 
$pdf->Cell(40,10,'$saledate'); 
$pdf->SetFont('arial','B',30); 
$pdf->Cell(40,10,'$price'); 
$pdf->Output(); 

?> 

這裏的錯誤

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\POS\v2\tuto1.php on line 7 
FPDF error: Some data has already been output, can't send PDF file 
+0

mysql_error()告訴了什麼? – 2011-06-08 17:30:24

回答

0

mysql_query()成功返回的資源nd查詢失敗狀態。由於某種原因查詢失敗,它返回false。在傳遞給mysql_fetch_array()之前測試查詢結果並顯示問題錯誤消息。

+0

我得到它的工作,並找出了它現在拉PDF文件的問題,但$ saledate&$價格的價值不是它的唯一印刷$ saledate&$價格。你能建議嗎? – darsh 2011-06-08 17:35:48

+0

執行'var_dump($ result);'並查看它返回的結果。相應地分配變量。 – 2011-06-08 17:37:47

0

SELECT * FROM sold WHERE imei = '87712839712893'返回錯誤。例如,查詢語法錯誤或模棱兩可,並且返回一個布爾值。您foreach之前,這樣做:

if(!$result){ 
    throw new Exception('Error: ' . mysql_error()); 
} 

一定要在執行是依賴於你的查詢結果的任何代碼之前捕獲異常。

+0

Downvoted是因爲'die()'不是一個很好的錯誤處理方法。我會建議一些更強大的東西 - 或者至少是不停止PHP併爲任何用戶打破頁面的東西。有一篇關於錯誤處理的優秀文章[這裏](http://www.phpfreaks.com/blog/or-die-must-die)。 – 2011-06-08 17:51:05

+0

感謝它的解決,因爲包含連接文件沒有連接,所以我在需要字段後鍵入mysql_connect和數據庫選擇權。 – darsh 2011-06-08 17:53:10

+0

@ lunchmeat317很好閱讀,謝謝。我會保持我的帖子相同,以便您的評論保持相關。 – wanovak 2011-06-09 14:10:38

2

我相信你需要使用mysql_fetch_object而不是mysql_fetch_array。後者只會做數字指數。 (我認爲mysql_fetch_assoc也可以。)

我不知道如果你只需要檢索一行,你是否需要這樣做,但我通常會在一個while循環中包裝mysql的提取結果。我想重寫代碼如下所示:

require('fpdf.php'); 
include ('connection.php'); 

$pdf=new FPDF(); 
$pdf->AddPage(); 

$data = mysql_query("SELECT * FROM sold WHERE imei = '87712839712893'"); 

while ($result = mysql_fetch_assoc($data)) 
(
    $pdf->SetFont('arial','B',10); 
    $pdf->Cell(40,10,'$result["saledate"]'); // edit: Note the double quotes. The error was probably caused by terminating the string early. 
    $pdf->SetFont('arial','B',30); 
    $pdf->Cell(40,10,'$result["sellingprice"]'); 
} 

// I don't know if the pdf Cell() command numeric arguments need to change or not. If they do, change them. 

$pdf->Output(); 

?> 

這有讓你在表中查詢多行輸出爲PDF格式的附加值。

除此之外,檢查您的SQL語句,並確保它是正確的。

+0

謝謝我嘗試了你的方式,但它給出了一個解析錯誤:解析錯誤:語法錯誤,意外的T_STRING在C:\ xampp \ htdocs \ POS \ v2 \ tuto1.php行37 – darsh 2011-06-08 17:56:39

+0

@Darsh這是一個語法錯誤 - 我認爲我知道問題是什麼。編輯我的答案。但是,這樣的錯誤應該很容易被發現 - 你是否嘗試編輯代碼? – 2011-06-08 18:05:04

+0

感謝您的建議。我沒有做任何改變,只是用開放的大括號替換彎曲的繃帶。另外,我用雙引號編輯了它的代碼,它生成一個PDF但不從MYSQL數據庫中提取出它的值,直接在pdf頁面上打印沒有值:$ result [「saledate」] $ result [「sellingprice」] – darsh 2011-06-08 18:16:20