2011-06-08 60 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