我在尝试使用PHP将数据从MYSQL导出为PDF时遇到错误
这是我的PHP代码:
<?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 :(得分:2)
我相信您需要使用mysql_fetch_object
,而不是mysql_fetch_array
。后者只会做数字索引。 (我认为mysql_fetch_assoc
也会起作用。)
如果您只检索一行,我不知道您是否需要执行此操作,但我通常会在while循环中包装mysql fetch结果。我会像这样重写你的代码:
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语句并确保它是正确的。
答案 1 :(得分:0)
mysql_query()
返回有关失败时查询成功和状态的资源。由于某些原因查询失败,它返回false。在将查询结果传递给mysql_fetch_array()
并显示问题错误消息之前测试它。
答案 2 :(得分:0)
SELECT * FROM sold WHERE imei = '87712839712893'
正在返回错误。例如,查询语法错误或含糊不清,并返回bool。在foreach
之前,请执行以下操作:
if(!$result){
throw new Exception('Error: ' . mysql_error());
}
确保在执行任何依赖于查询结果的代码之前捕获异常。