How to add queried rows with same values? - php

I am new to PHP. I have a table that stores the transactions bought. I am to summarize the transactions that happens in between two dates. For example: 2014-03-21 to 2014-03-23
I'm placing this in a fpdf :)
Here's my query:
<?php
$query = "SELECT * FROM tbl_items INNER JOIN tbl_receipts ON tbl_items.item_id=tbl_receipts.item_id WHERE receiptdate >= '$sdate' && receiptdate <='$ldate' ORDER BY tbl_items.item_id";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$addtotal = 0;
$counter = 1;
if (mysql_num_rows($result) != 0) {
while ($row = mysql_fetch_assoc($result)) {
$totaladd = $row['quantity_bought'] * $row['itemquantity_price'];
$item = $row['item_description'];
$num = $row['quantity_bought'];
$pdf->Cell(15, 13, '', 0, 0, 'C');
$pdf->Cell(15, 6, $counter, 1, 0, 'R');
$pdf->Cell(60, 6, $row['item_description'], 1, 0, 'L');
$pdf->Cell(20, 6, $row['quantity_bought'], 1, 0, 'R');
$pdf->Cell(30, 6, $row['itemquantity_price'], 1, 0, 'R');
$pdf->Cell(30, 6, "$totaladd.00", 1, 0, 'R');
$pdf->Ln(6);
$addtotal = $addtotal + $totaladd;
$counter++;
}
}
$pdf->Cell(15, 15, '', 0, 0, 'C');
$pdf->Cell(15, 6, '', 1, 0, 'R');
$pdf->Cell(60, 6, 'SUB-TOTAL', 1, 0, 'L');
$pdf->Cell(20, 6, '', 1, 0, 'R');
$pdf->Cell(30, 6, '', 1, 0, 'R');
$pdf->Cell(30, 6, "$addtotal.00", 1, 0, 'R');
$pdf->Ln(4);
?>
However, after summarizing, I have multiple rows for items with same item_description. I want to add those item quantities to avoid repetition. How can I do it?

Personally, I pass by the array, or I accumulate on the key and then I browse the array.
for example:
$array = array();
while($row = mysql_fetch_assoc($result)){
$array[$row['item_description']]['quantity_bought'] = $row['quantity_bought'];
$array[$row['item_description']]['itemquantity_price'] = $row['itemquantity_price'];
...
}
foreach($array as $item_description => $array_detail){
$item = $item_description;
foreach($array_detail as $key => $value){
if ($key == 'quantity_bought') $num = $value;
...
}
}

Related

data not exist after saved in pdf format (fpdf)

I use fpdf to create pdf documents in php(codeigniter). the data to be printed has appeared in the pdf preview of google chrome. but when the data has been saved in the pdf document format, the data does not appear
this is my code:
public function laporan()
{
$bulan1 = $this->input->post('bulan1');
$bulan2 = $this->input->post('bulan2');
$tanggal = array(
'tanggal1'=>$bulan1,
'tanggal2'=>$bulan2
);
$query = "SELECT costumers.nama AS costumer, alats.nama AS alat, DATE(transaksis.tanggal_ambil) AS tanggal_ambil,DATE(transaksis.tanggal_kembali) AS tanggal_kembali FROM costumers,transaksis,alats WHERE costumers.id=transaksis.costumer_id AND transaksis.alat_id=alats.id AND DATE(transaksis.created_at) BETWEEN '$bulan1' AND '$bulan2' ORDER BY transaksis.created_at DESC";
$data = $this->UserModel->query_umum($query)->result();
$header = array(
array("label"=>"No", "length"=>8, "align"=>"L"),
array("label"=>"Peminjam", "length"=>50, "align"=>"L"),
array("label"=>"Nama Alat", "length"=>60, "align"=>"L"),
array("label"=>"Tanggal Kirim", "length"=>30, "align"=>"L"),
array("label"=>"Tanggal Pengembalian", "length"=>40, "align"=>"L")
);
$this->cetak_laporan($header,$data,$tanggal);
}
public function cetak_laporan($header,$data,$tanggal)
{
$laporan = new FPDF();
$laporan->AddPage();
$laporan->SetFont('Arial','B',12);
$laporan->Image(base_url('asset/img/logo-dewiratih.png'),5,4,30,10);
$laporan->SetY(4);
$laporan->SetX(37);
$laporan->Cell(100,5, "CV. DEWI RATIH", 0, 1, 'L');
$laporan->SetFont('Arial','',6);
$laporan->SetX(37);
$laporan->Cell(100,2, "CONTRACTOR-SUPLIER-HEAVY EQUIPMENT RENTAL-STONES CRUISER", 0, 1, 'L');
$laporan->SetX(37);
$laporan->Cell(100,2, "Jl. Laut Mororejo Kaliwungu Kendal-Jateng 51372", 0, 1, 'L');
$laporan->SetX(37);
$laporan->Cell(100,2, "Telp/Fax (024) 8666225, Email : dewiratih_99#yahoo.com", 0, 1, 'L');
$laporan->SetLineWidth(0.5);
$laporan->Line(3,16,205,16);
// $pdf->Line(1,3.2,28.5,3.2);
$laporan->SetLineWidth(0);
$laporan->SetFont('Arial','B',14);
$laporan->Cell(0,15, "LAPORAN PEMINJAMAN ALAT", 0, 1, 'C');
// $pdf->SetFont('Arial','',12);
// $pdf->Cell(168,5,"Penyewa : ",0,1,'L');
$laporan->SetFont('Arial','',9);
// foreach ($tanggal as $tgl) {
$laporan->Cell(168,5,"Laporan dari tanggal : ".$tanggal['tanggal1']." Sampai ".$tanggal['tanggal2'],0,1,'L');
// }
$laporan->SetFont('Arial','B',10);
foreach ($header as $kolom) {
$laporan->Cell($kolom['length'], 5, $kolom['label'], 1, '0', $kolom['align'], false);
}
$laporan->Ln();
// $fill=false;
$laporan->SetFont('Arial','',10);
$no= 0;
foreach ($data as $baris) {
$i = 0;
$laporan->Cell(8, 5, $no+1, 1, '0', $kolom['align'], false);
foreach ($baris as $cell) {
$laporan->Cell($header[$i+1]['length'], 5, $cell, 1, '0', $kolom['align'], false);
$i++;
}
$no++;
$laporan->Ln();
}
// $pdf->Ln();
$laporan->Cell(25,5,"Keterangan : ",0,0,'L');
$laporan->Output("Laporan Peminjaman.pdf","I");
}
If you want to display the document first before the user can optionally download it, then you should consider using GET as a query string instead of POST method for $bulan1 & $bulan2.
When you are previewing your pdf document from previous page, it actually sending your POST variable ($bulan1 & $bulan2), but when you save it, the browser just making a request without the POST data on it, it can be seen on your saved document that it misses the $bulan1 & $bulan2 value.
I checked your and all is well :) (google chrome, adobbe reader, foxit reader).
Check my code:
public function laporan()
{
$bulan1 = $this->input->post('bulan1');
$bulan2 = $this->input->post('bulan2');
$tanggal = array(
'tanggal1' => '1111',
'tanggal2' => '2222',
);
$data = [];
for ($i = 0; $i <= 3; $i++) {
for ($i2 = 0; $i2 <= 3; $i2++) {
$data[$i][$i2] = random_string('alnum', 5);
}
}
$header = array(
array("label" => "No", "length" => 8, "align" => "L"),
array("label" => "Peminjam", "length" => 50, "align" => "L"),
array("label" => "Nama Alat", "length" => 60, "align" => "L"),
array("label" => "Tanggal Kirim", "length" => 30, "align" => "L"),
array("label" => "Tanggal Pengembalian", "length" => 40, "align" => "L"),
);
$this->cetak_laporan($header, $data, $tanggal);
}
public function cetak_laporan($header, $data, $tanggal)
{
$laporan = new FPDF();
$laporan->AddPage();
$laporan->SetFont('Arial', 'B', 12);
$laporan->Image('https://wiki.maemo.org/images/thumb/d/de/Maemo.org_logo_contest_sample1_bundyo.png/300px-Maemo.org_logo_contest_sample1_bundyo.png', 5, 4, 30, 10);
$laporan->SetY(4);
$laporan->SetX(37);
$laporan->Cell(100, 5, "CV. DEWI RATIH", 0, 1, 'L');
$laporan->SetFont('Arial', '', 6);
$laporan->SetX(37);
$laporan->Cell(100, 2, "CONTRACTOR-SUPLIER-HEAVY EQUIPMENT RENTAL-STONES CRUISER", 0, 1, 'L');
$laporan->SetX(37);
$laporan->Cell(100, 2, "Jl. Laut Mororejo Kaliwungu Kendal-Jateng 51372", 0, 1, 'L');
$laporan->SetX(37);
$laporan->Cell(100, 2, "Telp/Fax (024) 8666225, Email : dewiratih_99#yahoo.com", 0, 1, 'L');
$laporan->SetLineWidth(0.5);
$laporan->Line(3, 16, 205, 16);
// $pdf->Line(1,3.2,28.5,3.2);
$laporan->SetLineWidth(0);
$laporan->SetFont('Arial', 'B', 14);
$laporan->Cell(0, 15, "LAPORAN PEMINJAMAN ALAT", 0, 1, 'C');
// $pdf->SetFont('Arial','',12);
// $pdf->Cell(168,5,"Penyewa : ",0,1,'L');
$laporan->SetFont('Arial', '', 9);
// foreach ($tanggal as $tgl) {
$laporan->Cell(168, 5, "Laporan dari tanggal : " . $tanggal['tanggal1'] . " Sampai " . $tanggal['tanggal2'], 0, 1, 'L');
// }
$laporan->SetFont('Arial', 'B', 10);
foreach ($header as $kolom) {
$laporan->Cell($kolom['length'], 5, $kolom['label'], 1, '0', $kolom['align'], false);
}
$laporan->Ln();
// $fill=false;
$laporan->SetFont('Arial', '', 10);
$no = 0;
foreach ($data as $baris) {
$i = 0;
$laporan->Cell(8, 5, $no + 1, 1, '0', $kolom['align'], false);
foreach ($baris as $cell) {
$laporan->Cell($header[$i + 1]['length'], 5, $cell, 1, '0', $kolom['align'], false);
$i++;
}
$no++;
$laporan->Ln();
}
// $pdf->Ln();
$laporan->Cell(25, 5, "Keterangan : ", 0, 0, 'L');
$laporan->Output("Laporan Peminjaman.pdf", "I");
}

Make text fit in a cell with fpdf

im making a pdf file using fpdf.. The fdf generated will show data in table form from the database. My problem is, when the data string is too long, it do not fit well in the table cell. Look below in column no 3:
Below is my full code:
<?php
require('fpdf17/fpdf.php');
require('db.php');
//create a FPDF object
$pdf=new FPDF();
$pdf->SetFont('Times','B',20); //set font for the whole page (font family, style, size)
$pdf->SetTextColor(0,0,0); //using RGB value
//set up a page
$pdf->AddPage('P'); //potrait orientation
$pdf->SetDisplayMode('default'); //using 100 percent zoom and the viewer's default layout
$icon = "files/icon.png";
$pdf->Cell (10);
$pdf->Cell(60, 60, $pdf->Image($icon, $pdf->GetX(), $pdf->GetY(), 33.78), 0, 0, 'L', false);
$pdf->SetFillColor(0,0,0);
$pdf->SetFont('Times', '', 12);
$pdf->SetXY(10, 30);
$pdf->Cell(10);
$pdf->Cell(30, 6, 'Retrieval Date' , 0, 0, '', 0);
date_default_timezone_set("Asia/Kuala_Lumpur"); //set default time zone
$pdf->Cell(30, 6, ': '.date("d/m/Y"), 0, 2, 'B', 0);
//Set x and y position for the main text, reduce font size and write content
$pdf->SetXY(20,40); //setting the position
$pdf->SetFont('Times', 'BU', 14);
$pdf->Write(12,'Absenteeism record for:');
$course_course_code = addslashes( filter_input( INPUT_GET,'course',FILTER_SANITIZE_STRING ) );
$data = "SELECT course_code, course_name FROM studentattendance
INNER JOIN course ON studentattendance.course_course_code=course.course_code WHERE course_course_code LIKE '$_GET[course]' GROUP BY course_code";
$result = $conn->query($data) or die("Error: ".mysqli_error($conn));
while($ser=mysqli_fetch_array($result)){
$course_code = $ser['course_code'];
$course_name = $ser['course_name'];
$pdf->SetFillColor(0,0,0);
$pdf->SetFont('Times', '', 12);
$pdf->SetY(50);
$pdf->Cell(10);
$pdf->SetX(20);
$pdf->Cell(30, 6, 'COURSE' , 0, 0, '', 0);
$pdf->Cell(30, 6, ': '.$course_code. ' - '.$course_name, 0, 2, 'B', 0);
}
//start first table
$pdf->SetFillColor(255,255,255);
$pdf->SetFont('Times', 'B', 12);
$pdf->SetXY(21,58);
$pdf->Cell(10, 6, 'No.', 1, 0, 'L', 1);
$pdf->Cell(25, 6, 'Matric no', 1, 0, 'L', 1);
$pdf->Cell(75, 6, 'Name', 1, 0, 'L', 1);
$pdf->Cell(25, 6, 'GROUP', 1, 0, 'L', 1);
$pdf->Cell(30, 6, 'Absenteeism %', 1, 0, 'L', 1);
$row_height = 6;
$y1_axis = 58;
$y1_axis = $y1_axis + $row_height;
$counter = 1;
$course_course_code = addslashes( filter_input( INPUT_GET,'course',FILTER_SANITIZE_STRING ) );
$data = "SELECT stud_matric, stud_name, group_group_code, getid,
SUM(studAtt_endTime - studAtt_startTime)/(course_contacthour_perWeek * 14) AS 'sum' FROM studentattendance
INNER JOIN course ON studentattendance.course_course_code=course.course_code
INNER JOIN student ON studentattendance.student_stud_matric=student.stud_matric
WHERE studAtt_status='0' AND course_course_code LIKE '$_GET[course]' GROUP BY getid ORDER BY sum DESC";
$result = $conn->query($data) or die("Error: ".mysqli_error($conn));
while($ser=mysqli_fetch_array($result)){
$stud_matric = $ser['stud_matric'];
$stud_name = $ser['stud_name'];
$group_group_code = $ser['group_group_code'];
$per=number_format($ser['sum'] * 100, 2)." %";
$pdf->SetFont('Times', '', 12);
$pdf->SetXY(21, $y1_axis);
$pdf->Cell(10, 6, $counter, 1, 0, 'L', 1);
$pdf->Cell(25, 6, $stud_matric, 1, 0, 'L', 1);
$pdf->Cell(75, 6, $stud_name, 1, 0, 'L', 1);
$pdf->Cell(25, 6, $group_group_code, 1, 0, 'L', 1);
$pdf->Cell(30, 6, $per, 1, 0, 'L', 1);
$pdf->Ln();
$y1_axis = $y1_axis + $row_height;
$counter++;
if ($counter % 34 === 0) {
$pdf->AddPage();
$y1_axis = 20;
}
}
//end first table
//Output the document
$pdf->Output("$course_code.pdf",'I');
?>
Please help me..
Change the size of the cell
$pdf->Cell(5, 6, 'No.', 1, 0, 'L', 1);
$pdf->Cell(25, 6, 'Matric no', 1, 0, 'L', 1);
$pdf->Cell(100, 6, 'Name', 1, 0, 'L', 1);
$pdf->Cell(25, 6, 'GROUP', 1, 0, 'L', 1);
$pdf->Cell(30, 6, 'Absenteeism %', 1, 0, 'L', 1);

Count entries in a JSON Array?

How do I count the entries I am scraping from JSON?
The below example has 6 entries, but as you can see.. if an entry is added, my code will ignore it. I could loop it 10 times and if it picks up nothing, then stop, but I think that's a bad way of doing it.
Is there any simple code that picks up 6 'seasons' in the following JSON?
MYPAGE.PHP
//Get the page
$str = file_get_contents('http://myjsonurl.here/');
$jsonarray = json_decode($str, true);
$season1 = $jsonarray['season_history'][0][0];
$season2 = $jsonarray['season_history'][1][0];
$season3 = $jsonarray['season_history'][2][0];
$season4 = $jsonarray['season_history'][3][0];
$season5 = $jsonarray['season_history'][4][0];
$season6 = $jsonarray['season_history'][5][0];
//the rest of the info here..
JSON
{
"season_history": [
["2006/07", 2715, 12, 11, 0, 45, 0, 0, 0, 1, 0, 0, 26, 0, 91, 169],
["2007/08", 2989, 15, 11, 0, 56, 0, 0, 0, 3, 0, 0, 18, 0, 95, 177],
["2008/09", 2564, 9, 10, 0, 20, 0, 0, 0, 2, 0, 0, 14, 0, 95, 138],
["2009/10", 2094, 12, 6, 0, 13, 0, 0, 0, 1, 0, 0, 8, 0, 92, 130],
["2010/11", 2208, 21, 4, 8, 28, 0, 0, 0, 1, 0, 0, 26, 0, 92, 176],
["2011/12", 521, 7, 0, 2, 6, 0, 0, 0, 0, 0, 0, 5, 146, 89, 49]
]
}
A foreach loop may be the approach you're looking for.
For example, this code would output the years for each season in your JSON data, regardless of how many seasons there were:
//Get the page
$str = file_get_contents('http://myjsonurl.here/');
$jsonarray = json_decode($str, true);
foreach($jsonarray['season_history'] as $season) {
echo $season[0] . PHP_EOL;
}
Alternatively, if you just need to know the number of seasons, this would be a solution:
//Get the page
$str = file_get_contents('http://myjsonurl.here/');
$jsonarray = json_decode($str, true);
$numberOfSeasons = count($jsonarray['season_history']);
You could combine that with a for loop as well, if you wanted:
for($i = 0; $i < $numberOfSeasons; $i++) {
echo $jsonarray['season_history'][$i][0];
}
Nevermind.. I figured it out... Here is the code I used.
//Get the page
$str = file_get_contents('http://myjsonurl.here/');
$jsonarray = json_decode($str, true);
//FOR EACH SEASON
foreach ($jsonarray['season_history'] as $var)
{
for ($i = 0; $i <= 15; $i++)
{
echo $var[$i];
//do more stuff here
}
}

How to Sum Columns of a Multi-Dimensional Array?

I have array data like :
[
'A1' => [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'A2' => [1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
'A3' => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
I want to add the column values and produce a flat array of sums.
I want answer like this:
[2, 1, 0, 0, 0, 0, 0, 0, 0, 0]
Are there any array functions in php to do this? Otherwise how can I do this?
There's always custom code:
function array_sum_rows($arr) {
$out = array();
foreach ($arr as $row) {
foreach ($row as $i => $val) {
$out[$i] = isset($out[$i]) ? $out[$i] + $val : $val;
}
}
return $out;
}
$multiArray = ... //your array
$sumArray = array();
$i = 1;
foreach ($multiArray as $key => $array) {
$sumArray[$i] = array_sum($array);
$i++;
}
This would work with your array. You will get an array
http://php.net/manual/en/function.array-sum.php
Unfortunately loses the actual index in the transpose:
function array_transpose($arr) {
return call_user_func_array(
'array_map',
array_merge(
array(NULL),
$arr
)
);
}
$transposedArray = array_transpose($myData);
$result = array_map('array_sum', $transposedArray);
var_dump($result);
But the indexes can be restored by
$result = array_combine(array_keys(end($myData)), $result);
"Transpose" the input array (rotate the data 90 degrees so that columns become rows), then feed the new "rows" to array_map() so that each has array_sum() called upon it.
Code: (Demo)
$array = [
'A1' => [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'A2' => [1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
'A3' => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
var_export(array_map('array_sum', array_map(null, ...array_values($array))));
*Calling array_values() is necessary before the spread operator (...) until using a php version that doesn't choke on string keys.
Produces flat output array: [2, 1, 0, 0, 0, 0, 0, 0, 0, 0]

limit data with same amount per page on library fpdf

I am using PHP and fpdf to generate my view in pdf. My problem is how to limit amount of data per page?
If I have 100 rows data, the result is 10 page. So I must Limit 10 rows per page.
I have this code :
<?php
define('FPDF_FONTPATH', 'font/');
require_once("../../includes/initialize.php");
class PDF extends FPDF {
function Header() {
$this->Image("../icon/banner.jpg", 40, 10, 15);
}
function Footer() {
$this->SetY(-15);
$this->SetFont("Arial", "I", 10);
$this->Cell(0, 10, "Page " . $this->PageNo() . "/{nb}", 0, 0, "C");
}
}
$filter = $_GET["filter"];
$value = $_GET["value"];
if (!empty($_GET["filter"]) && !empty($_GET["value"])) {
$query = "Select id_detail_ruang, id_ruang, id_barang, no_seri from detail_ruang
where ".$filter." = '".$value."'";
} else {
$query = "Select id_detail_ruang, id_ruang, id_barang, no_seri from detail_ruang";
}
$sql = mysql_query($query);
$data = array();
while ($row = mysql_fetch_assoc($sql)) {
array_push($data, $row);
}
$judul = "LAPORAN KERUSAKAN";
$header = array(
array("label" => "No. Detail Kerusakan", "length" => 25, "align" => "C"),
array("label" => "Kode Barang", "length" => 25, "align" => "C"),
array("label" => "Nama Barang", "length" => 50, "align" => "C"),
array("label" => "No Ruang", "length" => 50, "align" => "C")
);
$pdf = new PDF("L");
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont("Arial", "B", 7);
$pdf->Cell(0, 20, $judul, 0, 1, "C");
$pdf->SetFillColor(87, 190, 224);
$pdf->SetTextColor(33, 71, 84);
$pdf->SetDrawColor(255, 0, 25);
$pdf->SetAutoPageBreak(true, 30);
foreach ($header as $kolom) {
$pdf->Cell($kolom['length'], 5, $kolom['label'], 1, '0', $kolom['align'], true);
}
$pdf->Ln();
$pdf->SetFillColor(87, 190, 224);
$pdf->SetTextColor(33, 71, 84);
$pdf->SetFont('');
$fill = false;
foreach ($data as $baris) {
$i = 0;
foreach ($baris as $cell) {
$pdf->Cell($header[$i]['length'], 5, $cell, 1, '0', $kolom['align'], $fill);
$i++;
}
$fill = !$fill;
$pdf->Ln();
}
$pdf->Output();
?>
I'm try using SetAutoPageBreak()
Is it Possible to do it..?
How to do it..?
Thanks
Since you've already go the data in a PHP array, the simplest solution would be to use array_chunk():
define('TABLE_SIZE', 100);
$pages=array_chunk($data, TABLE_SIZE, true);
foreach ($page as $table) {
foreach ($table as $baris) {
$i = 0;
foreach ($baris as $cell) {
$pdf->Cell($header[$i]['length'], 5, $cell, 1, '0', $kolom['align'], $fill);
$i++;
}
}
if (count($table)==TABLE_SIZE) {
// do page break
}
}

Categories