PHP - Build A Report In Php
Hi,
I have to build some reports based on mysql queries. Nothing fancy, just text, columns... There are a lot of paid softwares but I can't (and don't want to) spend any $$ right now... So, considering that I want very simple reports almost like a table with heading and subtotals, I should write it myself. But I don't know how (still...). I'm looking for tips, tutorials, ebooks... anything that explains how to make a very simply report. Regards, Pedro. Similar TutorialsI need to email this report but I don't know where to start
I have included the report code.
<html> <head> <title>Customer Load Report</title> </head> <body> <h1>Customer Load Report</h1> <?php $custid=$_POST["Cust_ID"]; $connect =odbc_connect("removed"); if(!$connect) { exit("Connection Failed: " . $connect); } $sql="SELECT m1_DC.dbo.organizationlocations.cmlName ,m1_DC.dbo.SalesOrders.OMPSHIPPINGMETHODID ,m1_DC.dbo.SalesOrders.UOMPTRUCKNUMBER ,m1_DC.dbo.SalesOrders.ompCustomerPO ,m1_DC.dbo.SalesOrders.UOMPTOTALBOXCOUNT ,m1_DC.dbo.SalesOrders.UOMPVOLUMETOTAL ,m1_DC.dbo.organizationlocations.CMLADDRESSLINE1 ,m1_DC.dbo.organizationlocations.CMLADDRESSLINE2 ,m1_DC.dbo.organizationlocations.CMLCITY ,m1_DC.dbo.organizationlocations.CMLSTATE ,m1_DC.dbo.organizationlocations.CMLPOSTCODE ,m1_DC.dbo.SalesOrders.OMPREQUESTEDSHIPDATE ,m1_DC.dbo.SalesOrders.ompSalesOrderID ,convert(varchar(10),m1_DC.dbo.SalesOrders.ompRequestedShipDate,110) as ShipDate FROM m1_DC.dbo.SalesOrders LEFT OUTER JOIN m1_DC.dbo.organizationlocations ON ompshiporganizationid = cmlorganizationid AND ompshiplocationid = cmllocationid WHERE m1_DC.dbo.SalesOrders.ompCustomerOrganizationID='$custid' and (ompOrderDate>=CONVERT(VARCHAR(10),DATEADD(day, -7, getdate()),110) or convert(varchar(10),m1_DC.dbo.SalesOrders.ompRequestedShipDate,110) >=getdate())"; $result =odbc_exec($connect,$sql); if(!$result){ exit("Error in SQL"); } $data= ''; while (odbc_fetch_row($result)) { $cmlName=odbc_result($result,"cmlName"); $ompCustomerPO=odbc_result($result,"ompCustomerPO"); $UOMPTOTALBOXCOUNT=odbc_result($result,"UOMPTOTALBOXCOUNT"); $UOMPVOLUMETOTAL=odbc_result($result,"UOMPVOLUMETOTAL"); $CMLADDRESSLINE1=odbc_result($result,"CMLADDRESSLINE1"); $CMLADDRESSLINE2=odbc_result($result,"CMLADDRESSLINE2"); $CMLCITY=odbc_result($result,"CMLCITY"); $CMLSTATE=odbc_result($result,"CMLSTATE"); $CMLPOSTCODE=odbc_result($result,"CMLPOSTCODE"); $ompSalesOrderID=odbc_result($result,"ompSalesOrderID"); $ompRequestedShipDate=odbc_result($result,"ShipDate"); $data .= "<td style='text-align:left' > $ompCustomerPO</td>"; $data .= "<td style='text-align:left'> $UOMPTOTALBOXCOUNT</td>"; $data .= "<td style='text-align:left'> $UOMPVOLUMETOTAL</td>"; $data .= "<td style='text-align:left'> $CMLADDRESSLINE1</td>"; $data .= "<td style='text-align:left'> $CMLADDRESSLINE2</td>"; $data .= "<td style='text-align:left'> $CMLCITY</td>"; $data .= "<td style='text-align:left'> $CMLSTATE</td>"; $data .= "<td style='text-align:left'> $CMLPOSTCODE</td>"; $data .= "<td style='text-align:left'> $ompSalesOrderID</td>"; $data .= "<td style='text-align:left'> $ompRequestedShipDate</td></tr>"; } echo "<table><tr>"; echo "<th>PO</th>"; echo "<th>Box_count</th>"; echo "<th>Cubes</th>"; echo "<th>ADDRESSLINE</th>"; echo "<th>ADDRESS2</th>"; echo "<th>CITY</th>"; echo "<th>STATE</th>"; echo "<th>ZIP</th>"; echo "<th>Order_ID</th>"; echo "<th>Ship Date</th></tr>"; echo $data; odbc_close($connect); ?> </body> </html> Instead of breaking down and actually learning how to use ajax, I'm thinking about trying to do something so I don't need a page refresh every time, and the filtered data is nearly instant. I just use the session array var, and build a new array from the rows that meet the conditions. I'm thinking of loading a two dimensional array into a session var, then use some input buttons, and use the post vars to filter the array based on a set of predefined conditions. ie status = 0, status = 1. It's a fairly small number of conditions applied to two different fields. So, I need to access specific fields within a row, and essentially create a new array either including or excluding that row depending on whether it met the condition. I'm struggling on several parts. 1. not sure how to build the array so that I can access specific fields, then not sure how to access those fields. Do I do this..... to build the array? .... Code: [Select] while($row = mysql_fetch_assoc($result)){ $array[] = array($row['field1'], $row['field2']); } I was thinking about using a foreach and is_array() to get to each row... Code: [Select] foreach($array as $key => $value){ if(is_array){ foreach($value as $k => $v){ if($v[0] == 1){ //stuck here $v[0] is not a field, it's the first char of the string. not sure how to access a field $new_array[] = $value; //stuck here. I need to put the whole row back into the array if the condition was true. seems like I would have to use the field selectors and rebuild the array. } } } } What would you do? Open to any ideas. Good day, How can I create a pdf report on my web page pulling out data from my database. I have never done this before I just need an idea. Hi all, I have a few questions and like some input on how best to approach this, I have a form in which customers can order different size online ads, the form has fields such as customer name, sales rep name, date needed by etc, my issue is I want to be able to run a report on how many different size ads I'm building in a day or month, would using MySQL be my solution to this? My PHP form right now gathers the information entered and sends me an email. Hi guys, this is very urgent. Can anyone help me out..... I want to generate reports using php and MySQL. I have one table which includes customer_id, full_name, name_with_initials, address, contact_number and gender fields. I want to print the details of all the records of the table. It should be good if results will come on a PDF format. Thanks, ok. this may make now sense at all, I will try to explain as best as I can. anyways, what I need is for a mysql query to run that will pull all data from table payment between certain days. Then all the rows will show, but I want only one row with each cart_id(there will be multiple) to show. After it does that, in a new column on a table, all the payment types with the amount will show with a slash between each one. I want all of this in a table generated from a php loop. maybe a visual represenation will be better. I hope the picture I attached makes a bit more sense. Hi All, I am trying to generate a PDF report using the below code. the report is being generated perfectly. The problem that I face is that, while printing the report the browser disregards the "IF" condition that I have given in the code. Explanation : ----------------- It prints all the data in the MySQL database wherein I wanted the data to be printed only on a certain condition. How do I achieve this? Quote <?php mysql_connect('localhost','user','pass'); mysql_select_db('vaccine'); $array = mysql_query("SELECT cattle_n FROM vactbl"); $num_rows = mysql_num_rows($array); $array = mysql_query("SELECT * FROM vactbl"); $num_rows = mysql_num_rows($array); while($info = mysql_fetch_array( $array )) { $mas_date = $info['masdt']; $mas_time = strtotime($mas_date); $two_week = strtotime("+2 week"); $rpt_date = abs($two_week - $mas_time); if ($rpt_date >= 7776000) { require('mysql_table.php'); class PDF extends PDF_MySQL_Table { function Header() { //Title $this->SetFont('Arial','B',40); $this->Cell(0,6,'Cattle List',0,1,'C'); $this->Ln(10); //Ensure table header is output parent::Header(); } } //Connect to database $pdf=new PDF(); $pdf->AddPage(); //First table: put all columns automatically //$pdf->Table('select * from cattle_det order by no'); //$pdf->AddPage(); //Second table: specify 3 columns $pdf->AddCol('cattle_n',20,'Cattle','C'); $pdf->AddCol('masdt',40,'Mastitis Date', 'C'); $pdf->AddCol('fmdt',40,'FM Date','C'); $pdf->AddCol('onedt',40,'Vaccine1 Date','C'); $pdf->AddCol('twodt',40,'Vaccine2 Date','C'); $prop=array('HeaderColor'=>array(255,150,100), 'color1'=>array(210,245,255), 'color2'=>array(255,255,210), 'padding'=>2); $pdf->Table('select cattle_n, masdt, fmdt, onedt, twodt from vactbl order by cattle_n limit 0,10',$prop); $pdf->Output(); } else {} } ?> Hi all, For a logging tool I need to make some automated reports. On 1 page it needs to give for 4 clients the amount of calls per month for the last 12 months. Also it needs to give the amount of calls for the employees per month for the last 12 months. I was hoping you could help me with a better solution than seperate queries. Gr Ryflex Hello, I have a database with the following tables: students groups exams examDay relation master detail ======= ===== ===== ======= ====== ====== ===== idStudent idGroup idExam idExDay idRelation idMaster idDetail idGroup groupName examName exDate idGroup idGroup idMaster studName idExDay idRelation idExam idExam idStudent coursesAtt idExDay I am trying to make a report from the Master and Detail tables that will have the table header like this: Group | Examination Date | Student Name | Exam1 | Exam2| .... | Exam n in which Exam1, Exam2,... are the exams names and they had to take the values from coursesAtt column. Is this possible? I could make a view (doing joins and group by) by the results will be displayed on row. That's why I ask for your help. Thanks This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=314049.0 Hi I have a db that has the following Data for example: PolicyNumber, StoreId, ConsultantName,ClientName, ClientSurname I would like to have a report that will give me a list of policies done for that day seperated by store printed to PDF. So Basically Store - 12CEL 24Hr001 Bob Joe Soap 24Hr002 Bill Gill Henry Store - 1156 24Hr003 Luke Manfred Kiy 24Hr004 Peter Ursula Jent I currently use R&OS for pdf Printing http://www.ros.co.nz/pdf The Code below Gives me all policies, I just need to now seperate them in the PDF //include pdf class include ('class.ezpdf.php'); //Include PHP Mailer Class require("class.phpmailer.php"); //Connect to database mysql_connect("localhost", "root", ""); @mysql_select_db("mobility") or die("Unable to select database"); $queryP= mysql_query("SELECT * FROM tblpolicies WHERE CaptureDate='2006-04-03' ORDER BY StoreId"); $pdf =& new Cezpdf(); //$pdf->addJpegFromFile('policy.jpg',60,$pdf->y-750,500,0); $pdf->selectFont('./fonts/Helvetica.afm'); $p = 750; While($x=mysql_fetch_array($queryP)){ $pdf->addText(50,$p,7,"{$x['PolicyNumber']}"); $pdf->addText(80,$p,7,"{$x['StoreId']}"); $pdf->addText(120,$p,7,"{$x['NickName']}"); $pdf->addText(220,$p,7,"{$x['ClientsName']}"); $pdf->addText(330,$p,7,"{$x['DateReceived']}"); $pdf->addText(410,$p,7,"{$x['Comments']}"); $p = $p - 10; if($p == 10){ $pdf->ezNewPage(); $p = 750; } } $pdf->ezText("\n\n\n\n\n\n\n" . $body,16,array('justification'=>'centre')); $pdf->output(); $pdf->ezStream(); //write pdf stream to pdf file $pdfcode = $pdf->ezOutput(); $fp=fopen('policy.pdf','wb'); fwrite($fp,$pdfcode); fclose($fp); Hello i am working on an application where i want to count from a selected date to another date and query all entries my database right now is composed of the following sales_id barcode_id student_id type of lunch date i have created the count per day, but now dont know how to go about to query the results and the count for the month. Code: [Select] $query = 'SELECT COUNT(*) FROM `sales` WHERE `tlunch` = 1 AND DATE(date) = CURDATE()'; $result = mysql_query($query) or die('Sorry, we could not count the number of results: ' . mysql_error()); $free = mysql_result($result, 0); has any one done something similar hi, i looking for a design report like crystal report or active reports but for php the objective is creat a report using mysql data and save the template and load that report in a pdf file for print or save any one know something like that? i already use classes like class.ezpdf.php but i spend many hours creating complex reports, all is created using a text editor.. thanks for your help Hi there I have a PHP file that works perfectly when I run it in my browser (compiles a report and saves it to my server), however when run from Cron gives a totally different output. Below is the code, and below that is the output I get when run from Cron. <?php include("db_conn.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Customer Appreciation Project</title> </head> <body> <?php $date = date("Y-m-d"); $time = date("h:i:s",time()); $file = $date.".html"; $fp=@fopen("active_members/".$file, 'w'); $content = "<html><head><title>Active Members Report</title></head><body>"; $content = $content . "<h1>Active Members</h1>"; $content = $content . "<p><font size=1>Report run on ". $date . " at ". $time."</font></p>"; $fetch_members = mysql_query("SELECT * FROM membership_periods WHERE (membership_periods.Start_Date <= Now() AND membership_periods.End_Date >= Now()) ORDER BY Member_Number"); if (mysql_num_rows($fetch_members) == "0") { $content = $content . "<p>No results were found.</p>"; } else { $content = $content . "<table border=0 cellpadding=2 width=100%>"; $content = $content . "<tr><td><b>Member Number</b></td><td><b>Start Date</b></td><td><b>End Date</b></td><td><b>Affiliation</b></td><td><b>Voucher</b></td></tr>"; while($row = mysql_fetch_array($fetch_members)) { $content = $content . "<tr><td>". $row['Member_Number'] ."</td><td>". $row['Start_Date']."</td><td>". $row['End_Date'] ."</td>"; $Affiliation_ID = $row['Affiliation_Group_ID']; if (Affiliation_ID > 0) { $fetch_affiliation= mysql_query("SELECT * FROM affiliation_groups WHERE ID = '$Affiliation_ID'"); $Affiliation_Group_Name = mysql_result($fetch_affiliation, 0, "Affiliation_Group_Name"); $content = $content . "<td>". $Affiliation_Group_Name ."</td>"; } else { $content = $content . "<td> </td>"; } $Member_Number = $row['Member_Number']; $fetch_member_id = mysql_query("SELECT ID FROM members WHERE Member_Number = '$Member_Number'"); $Member_ID = mysql_result($fetch_member_id, 0, "ID"); $fetch_voucher = mysql_query("SELECT Voucher_ID FROM reward_assignments WHERE Member_ID = '$Member_ID' AND Reward_Valid_To >= Now()"); if (mysql_num_rows($fetch_voucher) > 0) { $Voucher_ID = mysql_result($fetch_voucher, 0, "Voucher_ID"); $fetch_voucher_no = mysql_query("SELECT Voucher_Number FROM reward_vouchers WHERE ID = '$Voucher_ID'"); $Voucher_Number = mysql_result($fetch_voucher_no, 0, "Voucher_Number"); } $content = $content . "<td>". $Voucher_Number ."</td></tr>"; $Affiliation_Group_Name = ""; $Voucher_Number = ""; } $content = $content . "</table>"; } $content = $content . "</body></html>"; fwrite($fp, $content); fclose($fp); ?> </body> </html> And this is the Output I get mailed to me when Cron job runs: PHP Deprecated: Comments starting with '#' are deprecated in /etc/php5/cli/conf.d/mcrypt.ini on line 1 in Unknown on line 0 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Customer Appreciation Project</title> </head> <body> PHP Notice: Use of undefined constant Affiliation_ID - assumed 'Affiliation_ID' in /var/www/reports/active_members.php on line 40 PHP Notice: Undefined variable: Voucher_Number in /var/www/reports/active_members.php on line 63 PHP Notice: Use of undefined constant Affiliation_ID - assumed 'Affiliation_ID' in /var/www/reports/active_members.php on line 40 PHP Notice: Use of undefined constant Affiliation_ID - assumed 'Affiliation_ID' in /var/www/reports/active_members.php on line 40 PHP Notice: Use of undefined constant Affiliation_ID - assumed 'Affiliation_ID' in /var/www/reports/active_members.php on line 40 PHP Notice: Use of undefined constant Affiliation_ID - assumed 'Affiliation_ID' in /var/www/reports/active_members.php on line 40 PHP Notice: Use of undefined constant Affiliation_ID - assumed 'Affiliation_ID' in /var/www/reports/active_members.php on line 40 PHP Notice: Use of undefined constant Affiliation_ID - assumed 'Affiliation_ID' in /var/www/reports/active_members.php on line 40 PHP Warning: fwrite() expects parameter 1 to be resource, boolean given in /var/www/reports/active_members.php on line 75 PHP Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/reports/active_members.php on line 76 </body> </html> Any assistance would be much appreciated. This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=314453.0 Hi Guys My site has a shout box, now and again people post inappropriate content and if a moderator is not online to mute them it doesnt look good for other users. I have written a snippet of code to report an offender. My goal is that if 3 different people report an offender the site auto mutes them. (manual mute function already exists for moderators) I setup a table that records the reporters name the offenders name the post id the message content and the time stamp. I have never been good at counting num rows etc and need some help in what direction to go in. My current code that inserts the reported content. Code: [Select] mysql_query("INSERT INTO `chicka_pets`.`records_sbreports` (`id`, `offender`, `reporter`, `post_id`, `post_content`, `timestamp`) VALUES ('', '$offender', '$username', '$id', '$sbmessage', '$timestamp')"); I am guessing that somewhere after that I need some sort of count numrows on the post id where reporter is NOT the same and then an if numrows >2 set offender to mute my problem is how to do the num rows bit where the reporters are unique? Any help is much appreciated Hi, How can I get others informations on another page by clicking on one row's value I have this code, but it doesn't work: while($row = mysql_fetch_array($result)) { echo "<tr><p>"; echo "<th><p>" . $row['fname'] . " " . $row['lname'] . "</p></th>"; echo"<th><p><a href='student.php?id='".$row['topic']."'\'>".$row['topic']."</p></a></th>"; echo "</tr>"; } echo "</table>"; Student.php <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("college", $con); $result = mysql_query("SELECT * FROM students"); $topic = $_Get['topic']; while($row = mysql_fetch_array($result)) { echo "<tr><p>"; echo "<th><p>" . $row['month']." " .$row['datetime']."</p></th>"; echo"<th><p>". $row['topic'] ."</p></th>"; echo "<th><p>" . $row['gender'] . "</p></th>"; echo "<th><p>" . $row['fname'] . " " . $row['lname'] . "</p></th>"; echo "<th ><p>" . $row['id'] . "</p></th>"; echo "</tr>"; echo "</table>"; mysql_close($con); } ?> This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=348555.0 I implemented the Content-Security-Policy (CSP). I also included the report-uri so it sends a POST request to myserver.com/csp-report.php test.php <?php header("Content-Security-Policy: default-src 'self'; report-uri http://127.0.0.1/csp-report.php"); ?>I attempted to run these two inline scripts in my test.php file. <img src="http://evil.example.com/image.png"> <script>alert('XSS');</script>nothing is saved in the report-uri file! However, using Firebug, the policy is working as it should. Kindly advise if I have the report-uri synthax wrongly. Thank you Edited by terungwa, 20 October 2014 - 09:06 AM. I'm using a woocommerce order report plugin, some customers order multiple products but order report shows only number of order and one product name: I want to see all product names: also I want to see customer notes it doesn't show up
<?php /** * Plugin Name: Custom Order Report * Description: Generates a report on individual WooCommerce products sold during a specified time period. * Version: 1.4.8 */ // Add the Product Sales Report to the WordPress admin add_action('admin_menu', 'hm_psrf_admin_menu'); function hm_psrf_admin_menu() { add_submenu_page('woocommerce', 'Custom Order Report', 'Custom Order Report', 'view_woocommerce_reports', 'hm_sbpf', 'hm_sbpf_page'); } function hm_psrf_default_report_settings() { return array( 'report_time' => '30d', 'report_start' => date('Y-m-d', current_time('timestamp') - (86400 * 31)), 'report_end' => date('Y-m-d', current_time('timestamp') - 86400), 'order_statuses' => array('wc-processing', 'wc-on-hold', 'wc-completed'), 'products' => 'all', 'product_cats' => array(), 'product_ids' => '', 'variations' => 0, 'orderby' => 'quantity', 'orderdir' => 'desc', 'fields' => array('product_id', 'product_sku', 'product_name', 'quantity_sold', 'gross_sales'), 'limit_on' => 0, 'limit' => 10, 'include_header' => 1, 'exclude_free' => 0 ); } // This function generates the Product Sales Report page HTML function hm_sbpf_page() { $savedReportSettings = get_option('hm_psr_report_settings'); if (isset($_POST['op']) && $_POST['op'] == 'preset-del' && !empty($_POST['r']) && isset($savedReportSettings[$_POST['r']])) { unset($savedReportSettings[$_POST['r']]); update_option('hm_psr_report_settings', $savedReportSettings); $_POST['r'] = 0; echo('<script type="text/javascript">location.href = location.href;</script>'); } $reportSettings = (empty($savedReportSettings) ? hm_psrf_default_report_settings() : array_merge(hm_psrf_default_report_settings(), $savedReportSettings[ isset($_POST['r']) && isset($savedReportSettings[$_POST['r']]) ? $_POST['r'] : 0 ] )); // For backwards compatibility with pre-1.4 versions if (!empty($reportSettings['cat'])) { $reportSettings['products'] = 'cats'; $reportSettings['product_cats'] = array($reportSettings['cat']); } $fieldOptions = array( 'order_id' => 'Order ID', /*'product_id' => 'Product ID',*/ 'customer_name' => 'Customer Name', /*'variation_id' => 'Variation ID',*/ 'city' => 'City', 'address' => 'Address', 'product_name' => 'Product Name', 'quantity_sold' => 'Quantity Sold', /*'product_sku' => 'Product SKU',*/ 'gross_sales' => 'Gross Sales', 'product_categories' => 'Schools', /*'variation_attributes' => 'Variation Attributes',*/ /*'gross_after_discount' => 'Gross Sales (After Discounts)'*/ 'ceremony_date' => 'Ceremony Date', 'ceremony_time' => 'Ceremony Time', ); include(dirname(__FILE__).'/admin.php'); } // Hook into WordPress init; this function performs report generation when // the admin form is submitted add_action('init', 'hm_sbpf_on_init', 9999); function hm_sbpf_on_init() { global $pagenow; // Check if we are in admin and on the report page if (!is_admin()) return; if ($pagenow == 'admin.php' && isset($_GET['page']) && $_GET['page'] == 'hm_sbpf' && !empty($_POST['hm_sbp_do_export'])) { // Verify the nonce check_admin_referer('hm_sbpf_do_export'); $newSettings = array_intersect_key($_POST, hm_psrf_default_report_settings()); foreach ($newSettings as $key => $value) if (!is_array($value)) $newSettings[$key] = htmlspecialchars($value); // Update the saved report settings $savedReportSettings = get_option('hm_psr_report_settings'); $savedReportSettings[0] = array_merge(hm_psrf_default_report_settings(), $newSettings); update_option('hm_psr_report_settings', $savedReportSettings); // Check if no fields are selected or if not downloading if (empty($_POST['fields']) || empty($_POST['hm_sbp_download'])) return; // Assemble the filename for the report download $filename = 'Product Sales - '; if (!empty($_POST['cat']) && is_numeric($_POST['cat'])) { $cat = get_term($_POST['cat'], 'product_cat'); if (!empty($cat->name)) $filename .= addslashes(html_entity_decode($cat->name)).' - '; } $filename .= date('Y-m-d', current_time('timestamp')).'.csv'; // Send headers header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="'.$filename.'"'); // Output the report header row (if applicable) and body $stdout = fopen('php://output', 'w'); if (!empty($_POST['include_header'])) hm_sbpf_export_header($stdout); hm_sbpf_export_body($stdout); exit; } } // This function outputs the report header row function hm_sbpf_export_header($dest, $return=false) { $header = array(); foreach ($_POST['fields'] as $field) { switch ($field) { case 'order_id': $header[] = 'Order ID'; break; case 'product_name': $header[] = 'Product Name'; break; case 'quantity_sold': $header[] = 'Quantity Sold'; break; case 'gross_sales': $header[] = 'Gross Sales'; break; case 'product_categories': $header[] = 'Schools'; break; case 'customer_name': $header[] = 'Customer Name'; break; case 'city': $header[] = 'City'; break; case 'address': $header[] = 'Address'; break; case 'ceremony_date': $header[] = 'Ceremony Date'; break; case 'ceremony_time': $header[] = 'Ceremony Time'; break; } } if ($return) return $header; fputcsv($dest, $header); } // This function generates and outputs the report body rows function hm_sbpf_export_body($dest, $return=false) { global $woocommerce, $wpdb; $product_ids = array(); if ($_POST['products'] == 'cats') { $cats = array(); foreach ($_POST['product_cats'] as $cat) if (is_numeric($cat)) $cats[] = $cat; $product_ids = get_objects_in_term($cats, 'product_cat'); } else if ($_POST['products'] == 'ids') { foreach (explode(',', $_POST['product_ids']) as $productId) { $productId = trim($productId); if (is_numeric($productId)) $product_ids[] = $productId; } } // Calculate report start and end dates (timestamps) switch ($_POST['report_time']) { case '0d': $end_date = strtotime('midnight', current_time('timestamp')); $start_date = $end_date; break; case '1d': $end_date = strtotime('midnight', current_time('timestamp')) - 86400; $start_date = $end_date; break; case '7d': $end_date = strtotime('midnight', current_time('timestamp')) - 86400; $start_date = $end_date - (86400 * 6); break; case '1cm': $start_date = strtotime(date('Y-m', current_time('timestamp')).'-01 midnight -1month'); $end_date = strtotime('+1month', $start_date) - 86400; break; case '0cm': $start_date = strtotime(date('Y-m', current_time('timestamp')).'-01 midnight'); $end_date = strtotime('+1month', $start_date) - 86400; break; case '+1cm': $start_date = strtotime(date('Y-m', current_time('timestamp')).'-01 midnight +1month'); $end_date = strtotime('+1month', $start_date) - 86400; break; case '+7d': $start_date = strtotime('midnight', current_time('timestamp')) + 86400; $end_date = $start_date + (86400 * 6); break; case '+30d': $start_date = strtotime('midnight', current_time('timestamp')) + 86400; $end_date = $start_date + (86400 * 29); break; case 'custom': $end_date = strtotime('midnight', strtotime($_POST['report_end'])); $start_date = strtotime('midnight', strtotime($_POST['report_start'])); break; default: // 30 days is the default $end_date = strtotime('midnight', current_time('timestamp')) - 86400; $start_date = $end_date - (86400 * 29); } // Assemble order by string $orderby = (in_array($_POST['orderby'], array('product_id', 'gross', 'gross_after_discount')) ? $_POST['orderby'] : 'quantity'); $orderby .= ' '.($_POST['orderdir'] == 'asc' ? 'ASC' : 'DESC'); // Create a new WC_Admin_Report object include_once($woocommerce->plugin_path().'/includes/admin/reports/class-wc-admin-report.php'); $wc_report = new WC_Admin_Report(); $wc_report->start_date = $start_date; $wc_report->end_date = $end_date; //echo(date('Y-m-d', $end_date)); $where_meta = array(); if ($_POST['products'] != 'all') { $where_meta[] = array( 'type' => 'order_item_meta', 'meta_key' => '_product_id', 'operator' => 'in', 'meta_value' => $product_ids ); } if (!empty($_POST['exclude_free'])) { $where_meta[] = array( 'meta_key' => '_line_total', 'meta_value' => 0, 'operator' => '!=', 'type' => 'order_item_meta' ); } // Get report data // Avoid max join size error $wpdb->query('SET SQL_BIG_SELECTS=1'); // Prevent plugins from overriding the order status filter add_filter('woocommerce_reports_order_statuses', 'hm_psrf_report_order_statuses', 9999); // Based on woocoommerce/includes/admin/reports/class-wc-report-sales-by-product.php $sold_products = $wc_report->get_order_report_data(array( 'data' => array( '_product_id' => array( 'type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => '', 'name' => 'product_id' ), '_qty' => array( 'type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => 'SUM', 'name' => 'quantity' ), '_line_subtotal' => array( 'type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => 'SUM', 'name' => 'gross' ), '_line_total' => array( 'type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => 'SUM', 'name' => 'gross_after_discount' ), /*usama*/ 'order_id' => array( 'type' => 'order_item', 'order_item_type' => 'line_item', 'function' => '', 'name' => 'order_id' ) /*usama*/ ), 'query_type' => 'get_results', 'group_by' => 'order_id', 'where_meta' => $where_meta, 'order_by' => $orderby, 'limit' => (!empty($_POST['limit_on']) && is_numeric($_POST['limit']) ? $_POST['limit'] : ''), 'filter_range' => ($_POST['report_time'] != 'all'), 'order_types' => wc_get_order_types('order_count'), 'order_status' => hm_psrf_report_order_statuses() )); // Remove report order statuses filter remove_filter('woocommerce_reports_order_statuses', 'hm_psrf_report_order_statuses', 9999); if ($return) $rows = array(); // Output report rows foreach ($sold_products as $product) { $row = array(); /*usama*/ $order = wc_get_order($product->order_id); $customerName = $order->get_billing_first_name().' '.$order->get_billing_last_name(); $billingCity = $order->get_billing_city(); $billingAddress1 = $order->get_billing_address_1(); //echo $product->order_id; //echo $customerName.$city.$billingAddress1; //echo '<pre>';print_r($order);exit; /*usama*/ foreach ($_POST['fields'] as $field) { switch ($field) { case 'order_id': $row[] = $product->order_id; break; case 'product_name': $row[] = html_entity_decode(get_the_title($product->product_id)); break; case 'quantity_sold': $row[] = $product->quantity; break; case 'gross_sales': $row[] = $product->gross; break; /*case 'variation_id': $row[] = (empty($product->variation_id) ? '' : $product->variation_id); break; case 'product_sku': $row[] = get_post_meta($product->product_id, '_sku', true); break;*/ case 'product_categories': $terms = get_the_terms($product->product_id, 'product_cat'); if (empty($terms)) { $row[] = ''; } else { $categories = array(); foreach ($terms as $term) $categories[] = $term->name; $row[] = implode(', ', $categories); } break; case 'customer_name': $row[] = $customerName; break; case 'city': $row[] = $billingCity; break; case 'address': $row[] = $billingAddress1; break; /*case 'gross_after_discount': $row[] = $product->gross_after_discount; break;*/ /*usama*/ case 'ceremony_date': $row[] = $order->get_meta( '_billing_myfield12', true ); break; case 'ceremony_time': $row[] = $order->get_meta( '_billing_myfield13', true ); break; } } if ($return) $rows[] = $row; else fputcsv($dest, $row); } if ($return) return $rows; } add_action('admin_enqueue_scripts', 'hm_psrf_admin_enqueue_scripts'); function hm_psrf_admin_enqueue_scripts() { wp_enqueue_style('hm_psrf_admin_style', plugins_url('css/hm-product-sales-report.css', __FILE__)); wp_enqueue_style('pikaday', plugins_url('css/pikaday.css', __FILE__)); wp_enqueue_script('moment', plugins_url('js/moment.min.js', __FILE__)); wp_enqueue_script('pikaday', plugins_url('js/pikaday.js', __FILE__)); } // Schedulable email report hook add_filter('pp_wc_get_schedulable_email_reports', 'hm_psrf_add_schedulable_email_reports'); function hm_psrf_add_schedulable_email_reports($reports) { $reports['hm_psr'] = array( 'name' => 'Product Sales Report', 'callback' => 'hm_psrf_run_scheduled_report', 'reports' => array( 'last' => 'Last used settings' ) ); return $reports; } function hm_psrf_run_scheduled_report($reportId, $start, $end, $args=array(), $output=false) { $savedReportSettings = get_option('hm_psr_report_settings'); if (!isset($savedReportSettings[0])) return false; $prevPost = $_POST; $_POST = $savedReportSettings[0]; $_POST['report_time'] = 'custom'; $_POST['report_start'] = date('Y-m-d', $start); $_POST['report_end'] = date('Y-m-d', $end); $_POST = array_merge($_POST, array_intersect_key($args, $_POST)); if ($output) { echo('<table><thead><tr>'); foreach (hm_sbpf_export_header(null, true) as $heading) { echo("<th>$heading</th>"); } echo('</tr></thead><tbody>'); foreach (hm_sbpf_export_body(null, true) as $row) { echo('<tr>'); foreach ($row as $cell) echo('<td>'.htmlspecialchars($cell).'</td>'); echo('</tr>'); } echo('</tbody></table>'); $_POST = $prevPost; return; } $filename = get_temp_dir().'/Product Sales Report.csv'; $out = fopen($filename, 'w'); if (!empty($_POST['include_header'])) hm_sbpf_export_header($out); hm_sbpf_export_body($out); fclose($out); $_POST = $prevPost; return $filename; } function hm_psrf_report_order_statuses() { $wcOrderStatuses = wc_get_order_statuses(); $orderStatuses = array(); if (!empty($_POST['order_statuses'])) { foreach ($_POST['order_statuses'] as $orderStatus) { if (isset($wcOrderStatuses[$orderStatus])) $orderStatuses[] = substr($orderStatus, 3); } } return $orderStatuses; } /* Review/donate notice */ register_activation_hook(__FILE__, 'hm_psrf_first_activate'); function hm_psrf_first_activate() { $pre = 'hm_psr'; $firstActivate = get_option($pre.'_first_activate'); if (empty($firstActivate)) { update_option($pre.'_first_activate', time()); } } if (is_admin() && get_option('hm_psr_rd_notice_hidden') != 1 && time() - get_option('hm_psr_first_activate') >= (14*86400)) { add_action('admin_notices', 'hm_psrf_rd_notice'); add_action('wp_ajax_hm_psrf_rd_notice_hide', 'hm_psrf_rd_notice_hide'); } function hm_psrf_rd_notice() { $pre = 'hm_psr'; $slug = 'product-sales-report-for-woocommerce'; echo(' <div id="'.$pre.'_rd_notice" class="updated notice is-dismissible"><p>Do you use the <strong>Product Sales Report</strong> plugin? Please support our free plugin by <a href="" target="_blank">making a donation</a>!product-sales-report-for-woocommerce Thanks!</p></div> <script>jQuery(document).ready(function($){$(\'#'.$pre.'_rd_notice\').on(\'click\', \'.notice-dismiss\', function(){jQuery.post(ajaxurl, {action:\'hm_psrf_rd_notice_hide\'})});});</script> '); } function hm_psrf_rd_notice_hide() { $pre = 'hm_psr'; update_option($pre.'_rd_notice_hidden', 1); } ?>
|