Excel generation from database using PEAR - php

I have a mysql table like this
product | date | price
mobile | jan-14| 150
laptop | jan-14| 480
mobile | feb-14| 172
laptop | feb-14| 389
By using below code i got an output like this
product |jan 14 |feb 14|
mobile | 150 | 172 |
laptop | 480 | 389 |
My PHP code(PEAR)
<?php writer, query fetching, worksheet,workbook, etc..on here
$product=array();
$date1=array();
$price=array();
while($rr=mysql_fetch_array($result))
{
$col=0;
$product[$rr['product']]=$rr['product'];
$date1[$rr['date']]=$rr['date'];
$price[$rr['prodcut']][$rr['date']]=$rr['price'];
}
$row=1;
$col=1;
foreach($date1 as $tkey=>$t)
{
$worksheet->write($row,$col++,$t);
}
$row=2;
foreach($product as $dkey=>$d)
{
$col=0;
$worksheet->write($row,$col++,$d);
foreach($date1 as $tkey=>$t)
{
$worksheet->write($row,$col++,$price[$d][$t]);
}
$row++;
}
$workbook->close();
?>
But,I need an output along with total of product wise and date wise like below,
product |jan 14 |feb 14|Prod total
mobile | 150 | 172 | 322
laptop | 480 | 389 | 869
date total| 630 | 561 |
could anyone help me? Thanks advance.

Would be like this:
foreach($product as $dkey=>$d)
{
$col=0;
$worksheet->write($row,$col++,$d);
$total = 0;
foreach($date1 as $tkey=>$t)
{
$worksheet->write($row,$col++,$price[$d][$t]);
$total += $price[$d][$t];
}
$worksheet->write($row,$col++,$total);
$row++;
}

Related

Applying if-else condition to export selective records using PhpExcel

I need to export only those records whose column satisfies defined value.
Eg.
if(null !== ($this->f3->get('SESSION.userStatus')))
{
$userStatus = $this->f3->get('SESSION.userStatus');
}
This is how I tried to set cell values depending on set value:
$rowID = 5;
foreach ($results as $result)
{
if($result['status'] == $userStatus)
{
$objPHPExcel->getActiveSheet()->setCellValue('A'.$rowID, $result['fullname']);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$rowID, $result['checkin_date']);
}
else
{
$objPHPExcel->getActiveSheet()->removeRow($rowID);
}
$rowID++;
}
The file is exported with only those records that have defined "status" value.
But the problem is that rows whose criteria doesn't meet are filled with spaces and still occupies rows.
Here is how output looks like:
A | B | C | D
1 | | |
.
.
174 | | |
175 | | |
176 | | |
177 | | |
178 John | 2014| xyz | dfdf
179 Jack | 2015| jkl | dfdf
180 | | |
.
.
How can I fix it to get records starting with top row?
Eg.
1 | John | 2014 | xyz | dfdf
2 | Jack | 2015 | jkl | dfds
between
}
$rowID++;
put this
else
{
$objPHPExcel->getActiveSheet()->removeRow($rowID);
}
That will delete your blank rows.
Note, that you start with row 5 for some reason and do not test for max rows. Your code will still need some fixing up

Mysql query and php work out that can get items from DB and do the average

I have a stock table that has several items oderd by users and the item can be having different unit prices depending on the time they were ordered, so you can find an item has more than 5 entries with different prices like the below table:
+----+----------+----------+------------+-------------+-------+
| ID | unitCost | quantity | totalPrice | orderNumber | item |
+----+----------+----------+------------+-------------+-------+
| 1 | 20 | 5 | 100 | OD003 | Pen |
| 2 | 15 | 3 | 45 | OD004 | Pen |
| 3 | 22 | 10 | 220 | OD005 | Books |
| 4 | 13 | 7 | 91 | OD006 | Pen |
+----+----------+----------+------------+-------------+-------+
So am trying to get 10 pens from the table. And the logic should be like this
When I take the first and they are not enough from the first row, I will go to the next row and get the remaining quantity and if it will not be enough it will go to the next till I get the 10 pens that I needed.
Then the price of the 10 pens I get from the table will be the average of unit price of each pen i got.
Please help me solve this in mysql query.
I would get the result from mysql and put it inside array to loop it.
$total_order = 40; $price = 0;
foreach($result as $key => $value) {
if ($value['quantity'] < $total_order) {
$price += $value['quantity']*$value['unitCost'];
} else {
$price += $total_order*$value['unitCost'];
break; //exit loop and stop calculating
}
$total_order = $total_order-$value['quantity'];
}
You may need to tweak the code above a bit to meet your criteria. e.g: Pen price only.

view all products using group by in codeigniter

i've this client who has a employee list and he wants to display all employees of same category(in group), i'm sorry if i'm not able to explain, i will try to explain
----------------------------
id | e_id | e_pos | e_name
-----------------------------
1 | 142 | dev | abc
2 | 143 | sr.dev | bac
3 | 144 | intern | jlk
4 | 145 | dev | jlsd
5 | 146 | dev | asdf
6 | 147 | sr.dev | adsc
7 | 148 | intern | mlkn
8 | 149 | sr.dev | vjll
9 | 150 | dev | knmk
10 | 151 | dev | jlkm
----------------------------
how to show the output
Number of dev(5)
1) abc
2) jlsd
3) asdf
4) knmk
5) jlkm
Number of intern(2)
1) jlk
2) mlkn
Number of sr.dev(3)
1) bac
2) adsc
3) vjll
now the problem is i've tried this piece of code
$this->db->select('e_id,e_pos,e_name');
$this->db->group_by('e_pos');
$query = $this->db->get('emp'); // table name
if($query->num_rows() > 0)
{
return $query->result();
}
but the above code is not working, it's just showing dev and number of dev, i want to see all dev data.
dev
I'm using Codeigniter 2.2.0
You can use this CI code to get your data (detailed docs on this link):
$query = $this->db->query("YOUR QUERY");
and then pass in following query:
select test.e_pos, test.e_name, inn.cnt
from test
inner join
(SELECT e_pos, e_name, count(e_pos) as 'cnt'
FROM `test`
group by e_pos ) inn on test.e_pos = inn.e_pos
order by test.e_pos
You will get table like this, which you can then iterate to display result:
foreach ($query->result() as $row)
{
// echo data as desired
}

How to use $row results into mysqli_query?

How can I use $row results into a mysqli_query?
$result1 = mysqli_query($connect,"SELECT subcat_ID FROM subcategories WHERE cat_ID=$cat_ID");
$row=mysqli_fetch_array($result1);
$result2 = mysqli_query($connect,"SELECT subsubcat_name FROM subsubcategories WHERE subcat_ID='".$row['subcat_ID']."'");
while ($row = mysqli_fetch_array($result2)){
if (isset($row)){
echo $row['subsubcat_name'];
echo "<br>";
}
I don't get any error but I can't get it printed.
Any idea what I'm doing wrong?
Thanks for any help!
==================================================================================
1st edit
Because my problem isn't solved yet, I'm explaining it a bit more in depth:
My databases:
- categories: cat_ID, cat_name
- subcategories: subcat_ID, cat_ID, extra_cat_ID, subcat_name
- subsubcategories: subsubcat_ID, subcat_ID, subsubcat_name
At a certain point I get the value of a cat_ID (categories) through an url.
What I want to do is wherever cat_id of categories is the same value as the cat_id or extra_cat_ID like in subcategories (I also want to be able to print subcat_name), where subcat_ID of subcategories is the same as subcat_ID of subsubcategories ---> print subsubcat_name.
Categories
-------------------------
cat_ID | cat_name
------------------
4 | Baby & Kids
5 | Bicycles
6 | Boats
7 | Books & Comics
....
13 | Clothes & Accessories
....
35 | Sport & Fitness
36 | Study
....
38 | Toys & Games
....
Subcategories
-------------------------
subcat_ID | cat_ID | extra_cat_ID | subcat_name
------------------------------------------------
....
15 | 4 | 13 | Baby clothes
16 | 4 | 0 | Baby products
17 | 4 | 13 | Kids clothes
18 | 4 | 38 | Toys
19 | 5 | 0 | Bycicles
20 | 5 | 0 | Bycicle gear & Accessories
21 | 6 | 0 | Boat parts
22 | 6 | 0 | Other Boats
23 | 6 | 0 | Power Boats
24 | 6 | 0 | Sailboats
25 | 6 | 35 | Windsurf & Surfing
26 | 7 | 0 | Antiquarian
27 | 7 | 0 | Books
28 | 7 | 38 | Childrens books
29 | 7 | 0 | Comics
30 | 7 | 0 | Magazines & Newspapers
31 | 7 | 36 | Study & Training
Subsubcategories
-------------------------
subsubcat_ID | subcat_ID | subsubcat_name
-----------------------------------------
...
470 | 15 | Baptism outfits
471 | 15 | Bibs
472 | 15 | Body warmers
473 | 15 | Bodysuits
....
496 | 16 | Baby bath
497 | 16 | Baby books
498 | 16 | Baby inserts
499 | 16 | Baby monitors
....
548 | 17 | Belts
549 | 17 | Blouses & Shirts
550 | 17 | Body warmer
551 | 17 | Boots
....
....
740 | 26 | Music
741 | 26 | Navy
742 | 26 | Novel
743 | 26 | Photography
....
....
867 | 30 | Animals
868 | 30 | Arts and Culture
869 | 30 | Branch
870 | 30 | Cars
870 | 30 | Computers
....
....
etc.
I hope this clearout things a bit more.
Instead of running two queries you should use a JOIN.
For example this $query :
SELECT subcategories.cat_ID, subsubcategories.subsubcat_name
FROM subcategories
INNER JOIN subsubcategories
ON subcategories.cat_ID=subsubcategories.subcat_ID
WHERE subcategories.cat_ID = ?
Preparing your query is more appropriate/safe in this case:
/* create a prepared statement */
if ($result = mysqli_prepare($connect, $query)) {
/* bind parameters for markers */
mysqli_stmt_bind_param($result, "i", $cat_ID);
/* execute query */
mysqli_stmt_execute($result);
/* fetch data */
while ($row = mysqli_fetch_array($result)){
if (isset($row)){
echo $row['subsubcat_name'];
echo "<br>";
}
}
}
DEMO for SQL JOIN
Got it working. This is the code I used:
$result=mysqli_query($connect,"SELECT subcategories.cat_ID, subsubcategories.subsubcat_name FROM subcategories INNER JOIN subsubcategories ON subcategories.subcat_ID=subsubcategories.subcat_ID WHERE subcategories.cat_ID = $cat_ID OR subcategories.extra_cat_ID = $cat_ID");
while ($row = mysqli_fetch_array($result)){
echo $row['subsubcat_name'];
echo "<br>";
}
Though not sure it is the safe way to do it. Suggestions are always welcome.
Thanks to meda to showing me another approach tho it is not quite the same code.
Here is an example on how to use mysqli
object oriented
<?php
$connect= new mysqli("localhost","user","passwd","database");
if ($connect->connect_errno){
echo "could not connect";
}
$select = "SELECT * FROM tablename";
if($result = $connect->query($select)){
while($row = $result->fetch_object()){
echo $row->rowname."<br>";
}
}
else { echo 'no result'; }
$connect->close();
?>
Procedural Style
<?php
$connect= mysqli_connect("localhost","user","passwd","database");
if (mysqli_connect_errno()){
echo "could not connect";
}
$select = "SELECT * FROM tablename";
if($result = mysqli_query($connect,$select)){
while($row = mysqli_fetch_object($result)){
echo $row->rowname."<br>";
}
}
else { echo 'no result'; }
mysqli_close($connect);
?>

Autovivification in PHP

if I have this SQL query:
select substring(id for 2) as key,
yw, count(*)
from pref_money group by yw, key
returning number of users per week and per key:
key | yw | count
-----+---------+-------
VK | 2010-45 | 144
VK | 2010-44 | 79
MR | 2010-46 | 72
OK | 2010-48 | 415
FB | 2010-45 | 11
FB | 2010-44 | 8
MR | 2010-47 | 55
VK | 2010-47 | 136
DE | 2010-48 | 35
VK | 2010-46 | 124
MR | 2010-44 | 40
MR | 2010-45 | 58
FB | 2010-47 | 13
FB | 2010-46 | 13
OK | 2010-47 | 1834
MR | 2010-48 | 13
OK | 2010-46 | 1787
DE | 2010-44 | 83
DE | 2010-45 | 128
FB | 2010-48 | 4
OK | 2010-44 | 1099
OK | 2010-45 | 1684
DE | 2010-46 | 118
VK | 2010-48 | 29
DE | 2010-47 | 148
Then how can I please count those users? I'm trying:
$sth = $db->prepare('select substring(id for 2) as key, yw, count(*)
from pref_money group by yw, key');
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
++$users[$row['yw']][$row['key']];
print_r($users);
but get numerous errors.
I'm trying to get the data for a stacked bars diagram. The x-axis will show the week numbers and the y-axis will show number of users, grouped by the key strings.
Thank you! Alex
Are you trying to total the count column or just get number of rows returned? If the latter, php has a method for that. if the former, you need to make it $users[$row['yw']][$row['key'] += $row['count'] instead (assuming the array has already been created).
$sth = $db->prepare('select substring(id for 2) as key, yw, count(*)
from pref_money group by yw, key');
$sth->execute();
$users=array(); // register $users as an array.
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
if(!isset($users[$row['yw']])){// see if $users['whatever_key'] has already been set
$users[$row['yw']]=0;//if not, initialize it as a default starting value of 0
}
$users[$row['yw']]+=$row['key'];//now we won't get any nasty notices here about undeclared variables or keys..
print_r($users);

Categories