Generating PDF dynamically through fpdf - php
I am trying to generate a PDF dynamically using fpdf, but I am finding it very difficult. Only half of the result I could get. I want to generate my PDF like this:
And now I get a result like this:
Here is the code for PDF:
<?php
require('../fpdf/fpdf.php');
error_reporting(-1);
$id = $_GET['order_id'];
$db = new mysqli('localhost','root','','dbnme'); // use your credentials
class INVPDF extends FPDF
{
var $id;
var $today;
var $widths;
var $heads;
var $aligns;
var $formats;
var $db;
var $invTotal = 0;
var $advancePaid = 0;
//constructor
function INVPDF($invno, $db)
{
parent::fpdf();
$this->id = $invno;
$this->db = $db;
$this->today = date('jS M Y');
$this->heads = array('Item', 'UOM', 'Price', 'Qty', 'Disc %', 'Tax', 'Frt', 'Total' );
$this->widths = array (45, 15, 35, 15, 15, 20, 25, 30);
$this->aligns = array ('L','C','L','C','C','R','C', 'C');
$this->formats = array (0,0,0,0,0,1,0,0);
}
//Page header
function Header()
{
//Arial bold 15
//Title
include("../connect.php");
$ss1 = "select orders.sales_order_id, orders.company_id, lead_address.address, lead_address.address_category, lead_address.country, lead_address.state, lead_address.company_id, lead_address.city,lead_address.pin from orders INNER JOIN lead_address ON orders.company_id=lead_address.company_id where lead_address.address_category='Billing' AND orders.sales_order_id='".$_GET['order_id']."'";
$mq1 = mysql_query($ss1) or die(mysql_error());
$rr1 = mysql_fetch_array($mq1);
$billing = $rr1['address'];
list($line1, $line2, $line3) = explode(',',$billing);
$country = $rr1['country'];
$state = $rr1['state'];
$city = $rr1['city'];
$pin = $rr1['pin'];
//list($line1, $line2, $country, $state, $city, $pin) = explode(',',$address);
$ss2 = "select orders.sales_order_id, orders.company_id, lead_address.address, lead_address.address_category, lead_address.country, lead_address.state, lead_address.company_id, lead_address.city,lead_address.pin from orders INNER JOIN lead_address ON orders.company_id=lead_address.company_id where lead_address.address_category='Shipping' AND orders.sales_order_id='".$_GET['order_id']."'";
$mq2 = mysql_query($ss2) or die(mysql_error());
$rr2 = mysql_fetch_array($mq2);
$shipping = $rr2['address'];
$country1 = $rr2['country'];
$state1 = $rr2['state'];
$city1 = $rr2['city'];
$pin1 = $rr2['pin'];
//$email = $rr1['email'];
// $phone = $rr1['phone'];
// $mobile = $rr1['mobile'];
// $this->SetFont('Arial','B',15);
$this->setXY(10,20);
// $this->Cell(0,10,'INVOICE '.$this->id,0,2,'L');
$this->Image('logo.png',20,6,15);
$this->setXY(12,20);
//
$this->SetFont('OpenSans','',7);
$this->Cell(0,10,'Company Name. ',0,2,'L');
$this->Cell(0,0,'Address1, address2',0,2,'L');
$this->Cell(0,8,'city, stte',0,2,'L');
$this->Cell(0,2,'sales#company.com',0,2,'L');
//$this->Image('images/logo.png',10,6,60);
$this->SetFont('OpenSans','',7);
$this->setXY(12,50);
$this->Cell(0,-2,'Shipping Address',$this->id,0,2,0,'L');
$this->SetFont('OpenSans','',7);
$this->setXY(12,52);
$this ->MultiCell(57,22,'', 'LRTB', 'L', 1);
//$this->Cell(0,8,$name,$this->id,0,2,0,'L');
$this->setXY(12,55);
$this->Cell(0,-1,$shipping,$this->id,0,2,0,'L');
$this->setXY(12,53);
$this->Cell(0,10,$country." , ".$state,$this->id,0,2,0,'L');
$this->setXY(12,52);
$this->Cell(0,20,$city." , ".$pin,$this->id,0,2,0,'L');
$this->SetFont('OpenSans','',7);
$this->setXY(140,52);
$this ->MultiCell(57,22,'', 'LRTB', 'L', 1);
$this->setXY(140,34);
$this->Cell(0,30,'Billing Address',$this->id,0,2,0,'L');
$this->SetFont('OpenSans','',7);
$this->setXY(140,35);
$this->Cell(0,40,$line1." , ".$line2, $this->id,0,2,0,'L');
$this->setXY(140,35);
$this->Cell(0,49,$line3, $this->id,0,2,0,'L');
$this->setXY(140,33);
$this->Cell(0,62,$city1." , ".$pin1,$this->id,0,2,0,'L');
$this->setXY(140,33);
$this->Cell(0,70,$country1." , ".$state1,$this->id,0,2,0,'L');
//$this->setXY(12,65);
// $this->Cell(0,60,$phone,$this->id,0,2,0,'L');
//$this->setXY(12,65);
//$this->Cell(0,70,$mobile,$this->id,0,2,0,'L');
$this->SetFont('OpenSans','',7);
$this->setXY(10,5);
$this->Cell(0,10,'QUOTATION: '.$this->id,0,2,'R');
$this->SetFont('OpenSans','',7);
$until = date ('jS F Y', strtotime($this->today));
$this->Cell(0,0,'Date: '.$until,0,2,'R');
$this->SetFont('OpenSans','',7);
$this->Cell(0,10,'Due Date: Due on receipt',0,2,'R');
//Line break
$this->Ln(60);
for ($i=0; $i<9; $i++)
{
$this->Cell ($this->widths[$i], 8, $this->heads[$i], 1, 0, 'C', 1);
}
$this->Ln(8);
}
//Page footer
function Footer()
{
# $this->SetY(-50); // Uncomment to position at 5 cm from bottom
//Arial italic 8
$this->SetFont('OpenSans','',8);
$w = array_sum(array_slice($this->widths,0,3));
$this->Cell($w,12,'',1);
$this->Cell($this->widths[3],12,'',1,0,'C');
$this->setLeftMargin(45 + array_sum(array_slice($this->widths,0,4)));
$this->Cell($this->widths[5],4,'Sub Total',1);
$this->Cell($this->widths[6],4,number_format($this->invTotal,2),1,0,'R');
$this->Cell($this->widths[7],4,'USD',1,1,'C');
$this->Cell($this->widths[5],4,'Tax',1);
$this->Cell($this->widths[6],4,number_format($this->advancePaid,2),1,0,'R');
$this->Cell($this->widths[7],4,'USD',1,1,'C');
$this->Cell($this->widths[5],4,'Freight',1);
$this->Cell($this->widths[6],4,number_format($this->freight,2),1,0,'R');
$this->Cell($this->widths[7],4,'USD',1,1,'C');
$this->setLeftMargin(10);
$this->Cell($this->widths[5],4,'Total',1);
$this->Cell($this->widths[6],4,number_format($this->invTotal+$this->advancePaid,2),1,0,'R');
$this->Cell($this->widths[7],4,'USD',1,1,'C');
$this->SetFont('OpenSans','',6);
$this->Cell($w,10,'',0,0,'L');
$this->Cell(30,4,'Private Limited Company - TIN: 345sddd - PAN: sf43534',0,0,'C');
//$this->Cell($w,10,'');
$this->Cell(-30,12,'SRVC TAX: gddddddddddd - CIN: sdgdgdgdfgfdgfg',0,0,'C');
$this->Cell(30,20,'This document has been electronically generated and requires no physical signature or stamp.',0,0,'C');
}
function makeInvoice()
{
$sql = "select before_order_line_items.item, before_order_line_items.description, before_order_line_items.uom, before_order_line_items.selling_price, before_order_line_items.quantity, before_order_line_items.discount, before_order_line_items.tax, before_order_line_items.freight, before_order_line_items.tax_amount, before_order_line_items.total, items.name as iname, taxes.tax_id, taxes.name as tname, taxes.rate from before_order_line_items inner join items on before_order_line_items.item=items.item_id inner join taxes on before_order_line_items.tax=taxes.tax_id where before_order_line_items.sales_order_id = '".$_GET['order_id']."' ";
//echo $sql;
$res = $this->db->query($sql) or die($this->db->error);
$this->SetFont('OpenSans','',8);
if ($res->num_rows > 0)
{
while ($r = $res->fetch_row())
{
$this->invTotal += $r[10];
foreach ($r as $c => $value) {
//echo $value;
if ($this->formats[$c]) {
$value = number_format($value);
// echo $value;
}
$this->Cell($this->widths[$c],10,$value,'LR',0, $this->aligns[$c]);
}
$this->Ln();
//$amount = number_format($amount+$value);
}
}
}
} # invpdf class
$invno = $_GET['order_id'];
//Instantiation of inherited class
$pdf = new INVPDF($invno, $db);
$pdf->Open();
$pdf->AliasNbPages();
$pdf->setLeftMargin(10);
$pdf->setRightMargin(10);
$pdf->AddFont('OpenSans','','Opensans-Regular.php');
$pdf->SetFont('OpenSans','',7);
$pdf->SetDrawColor(102);
$pdf->SetFillColor(220);
$pdf->AddPage();
$pdf->makeInvoice();
$pdf->Output();
?>
Can somebody please help me how to do it? or is there any example code for something similar to this?
Looking at your actual pdf and expected pdf.. you are missing the no. column in table header.
This line-
$this->heads = array('Item', 'UOM', 'Price', 'Qty', 'Disc %', 'Tax', 'Frt', 'Total' );
should be-
$this->heads = array('No.', 'Item', 'UOM', 'Price', 'Qty', 'Disc %', 'Tax', 'Frt', 'Total' );
Related
Problem with the generation of csv file with condition
The following php code allows me to retrieve from a database the information of the orders of the day in order to export them in a csv file. However I also have a file ArticleStock.csv which contains information on the products: ID and Name but which are different from those present in the database. I found a way to link the two by adding the IDs from the ArticleStock file to the product reference field. Unfortunately this does not work well because the following program outputs a csv file with only the corresponding value found and not all the others <?php require_once 'dbconfig.php'; try { $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $sql = 'SELECT o.id_order , c.id_customer, c.firstname, c.lastname, a.address1, a.address2, a.postcode, a.city,a.phone, c.email, a.phone_mobile, od.product_id, od.product_name, p.reference, od.product_quantity, od.product_price, o.total_paid_tax_incl, c.id_customer, op.date_add, op.amount, op.payment_method FROM mod582_orders o INNER JOIN mod582_customer c ON o.id_customer = c.id_customer INNER JOIN mod582_address a ON o.id_address_delivery = a.id_address INNER JOIN mod582_order_detail od ON o.id_order = od.id_order INNER JOIN mod582_order_payment op ON o.reference = op.order_reference INNER JOIN mod582_product p ON p.id_product = od.product_id WHERE CAST(o.date_add AS DATE) like "2022-12%";'; $r = $pdo->query($sql); $tab = []; $tab[] = ['ORDNOORDER', 'ORDREFCUSORDER', 'ORDNOCOSTNUMBER', 'ORDNOCUSTOMER', 'ORDCUSTOMERCODE', 'ORDCUSCAT', 'ORDTYPE', 'ORDCURRENCY', 'ORDCURRENCYRATE', 'ORDDESIGNATION', 'ORDREPCODE', 'ORDPORT', 'ORDPORTTYPE', 'ORDPORTRATE', 'DEONOORDER', 'DEOCOMMENT', 'DEOCOUNTRY', 'DEONAME', 'DEOFIRSTNAME', 'DEOADDRESS1', 'DEOADDRESS2', 'DEOZIPCODE', 'DEOCITY', 'DEOPHONE', 'DEOMAIL', 'DEOPHONEPORTABLE', 'ODLNOORDER', 'ODLNOORDERLINE', 'ODLNOARTICLE', 'ODLARTDESIGN', 'REFERENCEPRODUIT', 'ODLQUANTITYORDER', 'ODLTTCCURUPRICE', 'ODLCODEPARCELLEFLEU', 'PAYNUMPAYMENT', 'PAYNOCUSTOMER', 'PAYNOORDER', 'PAYNOCURRENCY', 'PAYDATEPAYMENT', 'PAYPAYMENTTTCCUR', 'PAYCURRENCYRATE', 'PAYCONTREPARTIE']; $odrline = 0; // start with zero, as incremented before first written out $prevordernumber = 0; // pick a number that is not a valid order number $file = fopen("ArticlesStock.csv", "r"); $rowcsv = 0; while (!feof($file)) { $thisLine = fgets($file); $CSVData[$rowcsv] = explode(";", $thisLine); $rowcsv++; } fclose($file); $numRows = sizeof($CSVData); $rowcsv = 0; while ($rs = $r->fetch(PDO::FETCH_ASSOC)) { $refproduit = $rs['reference']; while ($rowcsv < $numRows) { if ($CSVData[$rowcsv][0] == $refproduit) { $idproduct = $CSVData[$rowcsv][0]; $nameproduct = $CSVData[$rowcsv][2]; if ($prevordernumber != $rs['id_order']) { $odrline++; $baseDate = strtotime($rs['date_add']); $formatDate = date("d/m/Y", $baseDate); $tab[] = [$rs['id_order'], $rs['id_order'], '17', '', 'AAA' . $rs['id_customer'], 'DET', 'O', 'EUR', '1', '', '115', 'D', 'P', '17', $rs['id_order'], '', 'FRA', $rs['firstname'], $rs['lastname'], $rs['address1'], $rs['address2'], $rs['postcode'], $rs['city'], $rs['phone'], $rs['email'], $rs['phone_mobile'], $rs['id_order'], $odrline, $idproduct, $nameproduct, $rs['reference'], $rs['product_quantity'], $rs['product_price'], '', '', '', $rs['id_order'], 'EUR', $formatDate, $rs['amount'], '1', 'VIR']; } else { $tab[] = [$rs['id_order'], $rs['id_order'], '17', '', 'AAA' . $rs['id_customer'], 'DET', 'O', 'EUR', '1', '', '115', 'D', 'P', '17', $rs['id_order'], '', 'FRA', $rs['firstname'], $rs['lastname'], $rs['address1'], $rs['address2'], $rs['postcode'], $rs['city'], $rs['phone'], $rs['email'], $rs['phone_mobile'], $rs['id_order'], $odrline, $rs['product_id'], $rs['product_name'], $rs['reference'], $rs['product_quantity'], $rs['product_price'], '', '', '', $rs['id_order'], '', '', '', '']; } } $rowcsv++; } $prevordernumber = $rs['id_order']; } // write $tab to file $date = date('d-m-y'); $fichier_csv = new SplFileObject('Vinistoria/Out/Commande/commande_STOCK_' . $date . '.csv', 'w'); foreach ($tab as $ligne) { $fichier_csv->fputcsv($ligne, ';'); } } catch (PDOException $e) { die("Could not connect to the database $dbname :" . $e->getMessage()); } CSV return by my code : And what i need : So i need to replace my csv file ODLNOARTICLE and ODLARTDESIGN by the IDs and Names of products present in the file ArticleStock whose ID is equal to the reference field of my products recovered by my SQL query
display only if has group of numbers
I need to return list with prices only if there have groups i try already if else empty not != nothing help any suggestions ? $usergroups = '11,9,10'; if (empty($usergroups)) { return; } $fields = 'MIN(IF(prices.percentage_discount = 0, prices.price, prices.price - (prices.price * prices.percentage_discount)/100)) as price, prices.usergroup_id as usergroup_id, ud.usergroup as usergroup_name'; $condition = db_quote(' prices.product_id = ?i AND prices.usergroup_id IN (?p) AND ud.lang_code = ?s', $product['product_id'], $usergroups, DESCR_SL); $group_by = 'usergroup_id'; $join = '?:usergroup_descriptions as ud ON ud.usergroup_id = prices.usergroup_id'; $opt_prices = db_get_array("SELECT ?p FROM ?:product_prices as prices LEFT JOIN ?p WHERE ?p GROUP BY ?p", $fields, $join, $condition, $group_by); $currencies = Registry::get('currencies'); foreach ($opt_prices as &$price) { $price['current'] = 0; if (in_array($price['usergroup_id'], $auth['usergroup_ids'])) { $price['current'] = 1; $product['price'] = $price['price']; } $price['price'] = number_format($price['price'], 2, '.', ' ') . ' $'; } $product['group_discounts'] = $opt_prices; } So i want display $product['group_discounts'] = $opt_prices; only if there is $usergroups = '11,9,10';
Answer your comment: You used that but ok here an example : <?php $usergroups = array('11','9','10'); $opt_prices='11'; if (in_array($opt_prices,$usergroups)){ echo 'yes'; }else{ echo 'no'; } ?>
Adding additional search for reference in Joomla component
I am using a real estate component that has a front-end admin area to view property listings. An additional field was added to a section called custom fields that is named Ref (Reference). In the admin listings I am trying to add an additional search that searches for that reference. There are three tables involved here: 1j0_cddir_jomestate Which holds the property listings information such as title and description. 1j0_cddir_fields which is the custom fields created. 1j0_cddir_content_has_fields and this holds the values of the custom fields I would need to join 1j0_cddir_content_has_fields "fields_id" with 1j0_cddir_fields "id" and 1j0_cddir_jomestate "id" must join 1j0_cddir_content_has_fields "content_id" I am struggling to figure out how to add this function to the models/admin_listings.php so that I may add that search input to the admin_listings view. <?php protected $text_prefix = 'COM_JOMESTATE'; protected $user; function __construct() { parent::__construct(); $this->user=JFactory::getUser(); $this->planID=$this->getPlanID(); } protected function getListQuery() { // Initialise variables. $db = $this->getDbo(); $query = $db->getQuery(true); if ($this->planID->profile=='company'){ $query->select( $this->getState( 'list.select', 'a.id AS id, a.title AS title, a.date_created, a.featured, a.users_id, a.published, '. 'c.title as category_title,a.date_publish,a.date_publish_down,ag.first_name,ag.last_name' ) ); }else{ $query->select( $this->getState( 'list.select', 'a.id AS id, a.title AS title, a.featured, a.date_created, a.users_id, a.published, '. 'c.title as category_title,a.date_publish,a.date_publish_down' ) ); } $query->from($db->quoteName('#__cddir_jomestate').' AS a'); $query->select('COUNT(l.id) AS viewHow, SUM(l.view_item) AS viewSum'); $query->join('LEFT', '#__cddir_statistic AS l ON (l.item_id = a.id AND l.extension=\'com_jomestate\')'); // Join over the categories. $query->join('LEFT', '#__cddir_categories AS c ON c.id = a.categories_id'); $query->join('LEFT', '#__cddir_categories AS e ON e.id = a.categories_address_id'); if ($this->planID->profile=='company'){ $query->join('LEFT', '#__cddir_agent AS ag ON a.users_id = ag.users_id'); $query->join('LEFT', '#__cddir_company AS co ON co.id = ag.company_id'); } $query->join('LEFT', '#__users AS u ON u.id = a.users_id'); // Filter by published published $published = $this->getState('filter.published'); if (is_numeric($published)) { $query->where('a.published = '.(int) $published); } // Filter by category. $categoryId = $this->getState('filter.categories_id'); if (is_numeric($categoryId) && $categoryId!=0) { $cat_tbl = JTable::getInstance('Category', 'JomcomdevTable'); $cat_tbl->load($categoryId); $rgt = $cat_tbl->rgt; $lft = $cat_tbl->lft; $baselevel = (int) $cat_tbl->level; $query->where('c.lft >= '.(int) $lft); $query->where('c.rgt <= '.(int) $rgt); } $search = $this->getState('filter.search'); if (!empty($search)) { if (stripos($search, 'id:') === 0) { $query->where('a.id = '.(int) substr($search, 3)); } else { $search = $db->Quote('%'.$db->escape($search, true).'%'); $query->where('(a.title LIKE '.$search.' OR a.alias LIKE '.$search.')'); } } if ($this->planID->profile=='company'){ $query->where('(a.users_id ='.(int) $this->user->id.' or co.users_id='.(int) $this->user->id.')'); } else $query->where('a.users_id ='.(int) $this->user->id); $sort = $this->getState('list.sort'); switch($sort) { case 'most_viewed': $query->order($db->escape('viewSum DESC, a.date_publish DESC')); break; case 'alfa': $query->order($db->escape('a.title, a.date_publish DESC')); break; case 'featured': $query->order($db->escape('a.featured DESC, a.date_publish DESC')); break; case 'latest': default: $query->order($db->escape('a.date_publish DESC')); } $query->group($db->escape('a.id')); return $query; } function getCategories() { $cat_array = array(array('v'=>'','t'=>JText::_('COM_JOMESTATE_ADM_ALL'))); $query = "SELECT title, id, level FROM #__cddir_categories WHERE extension='com_jomestate.jomestate' ORDER BY lft"; $data = $this->_getList($query); foreach ($data as $row): for ($i=1;$i<$row->level;$i++) $row->title=" ".$row->title; $temp_array=array('v'=>$row->id,'t'=>$row->title); array_push($cat_array,$temp_array); endforeach; return $cat_array; } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * #since 1.6 */ protected function populateState($ordering = null, $direction = null) { // Initialise variables. $app = JFactory::getApplication('site'); // Load the parameters. // $params = $app->getParams(); $params = JComponentHelper::getParams('com_jomestate'); $menu = $app->getMenu(); $this->active = $menu->getActive(); if ($this->active) { $menuParams = $this->active->params; $global = $menuParams->get('global_option'); if(!$global) { $paramsa = $menuParams->toArray(); $paramsb = $params->toArray(); foreach($paramsa AS $key=>$p) $paramsb[$key] = $p; $newObject = (object) $paramsb; $newObject->activeItemid = $this->active->id; $params->loadObject($newObject); } } $this->setState('params', $params); $limit = $this->getUserStateFromRequest($this->context.'.list.limit', 'jdItemsPerPage', $params->get('listing_per_page'), 'uint'); $this->setState('list.limit', $limit); $value = $app->getUserStateFromRequest($this->context . '.list.limitstart', 'limitstart', 0); $limitstart = ($limit != 0 ? (floor($value / $limit) * $limit) : 0); $this->setState('list.start', $limitstart); $search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search', '', 'string'); $this->setState('filter.search', $search); $categoryId = $this->getUserStateFromRequest($this->context.'.filter.categories_id', 'filter_category', '', 'string'); $this->setState('filter.categories_id', $categoryId); $sort = $this->getUserStateFromRequest($this->context.'.list.sort', 'jdItemsSort', 'latest', 'string'); $this->setState('list.sort', $sort); } public function getUserStateFromRequest($key, $request, $default = null, $type = 'none', $resetPage = true) { $app = JFactory::getApplication(); $old_state = $app->getUserState($key); $cur_state = (!is_null($old_state)) ? $old_state : $default; $new_state = JRequest::getVar($request, $old_state, 'default', $type); if (($cur_state != $new_state) && ($resetPage)) { JRequest::setVar('limitstart', 0); } // Save the new value only if it is set in this request. if ($new_state !== null) { $app->setUserState($key, $new_state); } else { $new_state = $cur_state; } return $new_state; } public function getUser() { return $this->user; } public function getToolbar() { $document = JFactory::getDocument(); $document->addStyleSheet('administrator/templates/system/css/system.css'); $document->addStyleSheet('components/com_jomestate/assets/css/backadmin.css'); $controller='admin_listings'; jimport('joomla.html.toolbar'); $bar = new JToolBar( 'toolbar' ); if(Joomla_Version::if3()) { $bar->appendButton( 'standard', 'new', JText::_('COM_JOMESTATE_ADM_ADD'), $controller.'.add', false ); $bar->appendButton( 'standard', 'publish', JText::_('COM_JOMESTATE_ADM_PUBLISH'), $controller.'.publish', false ); $bar->appendButton( 'standard', 'unpublish', JText::_('COM_JOMESTATE_ADM_UNPUBLISH'), $controller.'.unpublish', false ); $bar->appendButton( 'standard', 'delete', JText::_('COM_JOMESTATE_ADM_DELETE'), $controller.'.delete', false ); } else { $bar->appendButton( 'Frontend', 'new', JText::_('COM_JOMESTATE_ADM_ADD'), $controller.'.add', false ); $bar->appendButton( 'Frontend', 'publish', JText::_('COM_JOMESTATE_ADM_PUBLISH'), $controller.'.publish', false ); $bar->appendButton( 'Frontend', 'unpublish', JText::_('COM_JOMESTATE_ADM_UNPUBLISH'), $controller.'.unpublish', false ); $bar->appendButton( 'Frontend', 'delete', JText::_('COM_JOMESTATE_ADM_DELETE'), $controller.'.delete', false ); } return $bar->render(); }
FPDF - Generate multiple pdf in a single creation
I am trying to generate multiple (in cluster) pdf reports using fpdf in a single click in a php form. The test_center is the cluster of separate reports. When the submit button is clicked, it will call the php file of fpdf. And my codes aren't working yet. So far in my php: <?php $program="select distinct test_center from sa_sase_result where school_year = '$content' "; $prog=mysql_query($program); while($row = mysql_fetch_array($prog)) { echo '<option>' .$row['test_center'] . '</option>'; } $message = null; if($_SERVER["REQUEST_METHOD"] == "POST") { if(!isset($_POST['depchair'])) { } else if($_POST['depchair']=="") { } else { $input_depchair = addslashes($_POST['depchair']); $input_depchair = addslashes($_POST['depchair']); $pro_email="select control_no from sa_student_infoe y where y.test_center = '$input_depchair'"; $pro_address=mysql_query($pro_email); $address = mysql_result($pro_address, 0); } } ?> EDIT: Here's the generate_pdf.php file. <?php require('fpdf/fpdf.php'); mysql_connect("localhost", "root", "1234") or die(mysql_error()); mysql_select_db("final") or die(mysql_error()); $query = "SELECT * FROM sa_student_infoe, sa_student_edubg, sa_sase_result, sa_accounts"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result, MYSQL_BOTH)){ $control_no[] = $row['control_no']; $surname[] = $row['surname']; $fname[] = $row['fname']; $mname[] = $row['mname']; $app_no[] = $row['activation_code']; $schoolyear[] = $row['schoolyear']; $schl[] = $row['high_school']; $schl_ad[] = $row['address_school']; $apt[] = $row['aptitude']; $mth[] = $row['math']; $lng[] = $row['language']; $sci[] = $row['science']; $totgrd[] = $row['total_grade']; $sx[] = $row['sex']; } $ctrl_no = array_shift( $control_no ); $sname = array_shift( $surname ); $firstname = array_shift( $fname ); $midname = array_shift( $mname ); $appno = array_shift( $app_no ); $schyear = array_shift( $schoolyear ); $school = array_shift( $schl ); $school_ad = array_shift( $schl_ad ); $aptitude = array_shift( $apt ); $math = array_shift( $mth ); $lang = array_shift( $lng ); $science = array_shift( $sci ); $gr = array_shift( $totgrd ); $sex = array_shift( $sx ); $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial','', 12); $pdf->Cell(0, 0,'Mindanao State University', 0, 1, 'C'); $pdf->Cell(0, 10,'System Admission and Scholarship Examination (SASE)', 0, 1, 'C'); $pdf->Cell(0, 20,'REPORT OF RATING', 0, 1, 'C'); $pdf->Cell(30,5,'Control No:'); $pdf->Cell(100,5,$ctrl_no); $pdf->Cell(30,5,'School Year:'); $pdf->Cell(-160,5,$schyear); $pdf->Cell(30,15,'Activation Code:'); $pdf->Cell(10,15,' ' . $appno); $pdf->Cell(50,40,$sname); $pdf->Cell(50,40,$firstname); $pdf->Cell(-120,40,$midname); $pdf->Cell(15,50,'____________________________________________________________________'); $pdf->Cell(50,60,'LASTNAME'); $pdf->Cell(50,60,'FIRSTNAME'); $pdf->Cell(-50,60,'MIDDLENAME'); $pdf->Cell(-65,90,$school); $pdf->Cell(67,100,'____________________________________________________________________'); $pdf->Cell(-15,110,'SCHOOL'); $pdf->Cell(-52,140,$school_ad); $pdf->Cell(57,150,'____________________________________________________________________'); $pdf->Cell(-25,160,'SCHOOL ADDRESS'); $pdf->Cell(.1,190,'--------------------------------------------------------------------'); $pdf->Cell(-35,200,'--------------------------------------------------------------------'); $pdf->Cell(17,230,'AP(30):'); $pdf->Cell(18,230,$aptitude); $pdf->Cell(17,230,'LU(80):'); $pdf->Cell(18,230,$lang); $pdf->Cell(17,230,'MA(40):'); $pdf->Cell(18,230,$math); $pdf->Cell(17,230,'SC(30):'); $pdf->Cell(18,230,$science); $pdf->Cell(18,230,'GR(180):'); $pdf->Cell(-300,230,$gr); $pdf->Cell(-10,260,'SEX:'); $pdf->Output("pdf_reports/SASE_report_rating/".$ctrl_no.".pdf", "F"); ?>
js: $("#id_of_generate_it_button").click(function () { var N = 10;// ten pdf files will be generated and stored to the disk for (i = 0; i < N; i++) {// 'the loop' -- walk thru all parallel generation processes connected to the event parameter = N;// just to definite each single generated file $.get("generate.php?q=parameter", function (data) {// start the ajax process to generate single document // ?q=parameter i wrote just for passing to the php file some dependent parameter for each single file // pdf #i generated }); }// end for parallel generating N pdf files to the disk });//end click in generate.php: $query = "SELECT * FROM sa_student_infoe, sa_student_edubg, sa_sase_result, sa_accounts WHERE some_field = ' . $_REQUEST['q'] . '";// single record from all
Using json encode
I am trying to use json encode for the first time and need some insight to what I am doing wrong. It should look like this: { teams : [ ["2147483647", "9"],["2147483647", "6"],["2147483647", "4"],["11", "2147483647"],["5", "2147483647"],["12", "8"],["10", "3"],["2147483647", "7"], ], results : [ [ [[0, 1],[0, 1],[0, 1],[1, 0],[1, 0],[0, 0],[0, 0],[0, 1],], [[0, 0],[0, 0],[0, 0],[0, 0],], [[0, 0],[0, 0],], [[0, 0],[0, 0]] ] ] } But the data being returned looks like this:- {"teams":[["2147483647","10","5","12","11","2147483647","2147483647","2147483647"],["7","3","2147483647","8","2147483647","4","6","9"]],"results":[["0","0","0","0","0","0","0","0"],["0","0","0","0","0","0","0","0"]]} Code: public function getAutoCompleteData($tournID, $db) { $max = $this->max($tournID); $one = $this->tourn_info("1on1", $tournID); $total_matches = $max; $after_matches = $max / 2; $matches = $db->query($this->select("*", "matches", "leagueID='{$tournID}' AND league='tourn'")); while ($row = $db->fetchAssoc($matches)) { $clan1 = $this->getname($row['clan1'], $tournID, "tourn", $ac = NULL, 1, 1, $wc2 = 0); $clan2 = $this->getname($row['clan2'], $tournID, "tourn", $ac = NULL, 1, 1, $wc2 = 1); if ($row['matchno'] <= $after_matches) { $clan_one[] = $row['clan1']; $clan_two[] = $row['clan2']; $score_one[] = $row['score1']; $score_two[] = $row['score2']; } } $data = array( 'teams' => array( $clan_one, $clan_two ), 'results' => array( $score_one, $score_two ) ); return $data; } Where it shows teams, it should close the bracket ] every two teams? Hope someone can help.
Not saying this will fix your problem, but it may help you to understand PHP. class mustBeAClass{ protected function max($tnid){ // must have this function - can be public for outside method use } protected function tourn_info($typ, $tnid){ // must have this function - can be public for outside method use } protected function getname($arg0, $arg1, $arg2, $arg3, $arg4, $arg5, $arg6 = 0){ /* must have this function - can be public for outside method use notice that $arg6 is how you assign default to arguments */ } public function getAutoCompleteData($tournID, $db){ $db->open(); $max = $this->max($tournID); $one = $this->tourn_info("1on1", $tournID); // what is the point of this ---->>>> $total_matches = $max; $after_matches = $max / 2; // notice query issue below $matches = $db->query("SELECT * FROM matches WHERE leagueID ='$tournID' && league='tourn'")); // while loop has problems if($matches->num_rows < 1){ die('You have no matches'); } else{ while($row = $db->fetch_assoc()){ $clan1 = $this->getname($row['clan1'], $tournID, 'tourn', null, 1, 1, 0); $clan2 = $this->getname($row['clan2'], $tournID, 'tourn', null, 1, 1, 1); if($row['matchno'] <= $after_matches) { $clan_one[] = $row['clan1']; $clan_two[] = $row['clan2']; $score_one[] = $row['score1']; $score_two[] = $row['score2']; } } $data = array( 'teams' => array($clan_one, $clan_two), 'results' => array($score_one, $score_two) ); } $matches->free(); $db->close(); return $data; } } $cls = new mustBeAClass; echo json_encode($cls->getAutoCompleteData($tournId, $db)); Of course use the correct values for $tournId and your new mysqli(/*args*/) for $db.