I'm trying to find a way to export the content of a MySQL table to PDF format but the main issue I'm facing is trying to do it dynamically. I'm following the logic of the 5th tutorial provided in the Tutorials section on the site but I can't seem to be able to achieve it. Is there a way to do it efficiently with FPDF?
Here's the code I'm using:
(excluding the the contents of the ImprovedTable and FancyTable methods, which are basically the same as the ones provided in the example)
Code: Select all
//Simple table
function BasicTable($header,$data)
{
//Header
$w=array(20,30,55,25,20,20);
//Header
for($i=0; $i<count($header); $i++)
$this->Cell($w[$i],7,$header[$i],1,0,'C');
$this->Ln();
//Data
foreach ($data as $eachResult)
{
$this->Cell(20,6,$eachResult["id"],1);
$this->Cell(30,6,$eachResult["Name"],1);
//This is where my problem lies. Is there a way not to have to hardcode column names like this in the array?
}
}
$pdf=new PDF();
//Column titles
//$header = array('id','Name');
$header = array(); //creating an empty array to be filled with field names retrieved from MySQL query executed below
//Data loading
//*** Load MySQL Data ***//
$objConnect = Database::getConnection();
$query = "SELECT * FROM users";
$objQuery = $objConnect->query($query);
$colNames = $objQuery->fetch_fields();
//filling in $header array with column names (this part works and renders correctly on the PDF file)
foreach ($colNames as $colName)
{
$header[] = $colName->name;
}
$resultData = array();
for ($i=0; $i<$objQuery->num_rows; $i++)
{
$result = $objQuery->fetch_array();
array_push($resultData,$result);
}
//************************//
$pdf->SetFont('Arial','',10);
//*** Table 1 ***//
$pdf->AddPage();
//$pdf->Image('logo.gif',80,8,33); //I'm not using a logo so far, so I commented this line
$pdf->Ln(35);
$pdf->BasicTable($header,$resultData);
//Prompt user to download
$pdf->Output("export.pdf","D"); Thanks in advance (and I hope someone has the patience to read all this).