Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9149957
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T11:32:53+00:00 2026-06-17T11:32:53+00:00

I am having some trouble getting a postgres query to work within some php

  • 0

I am having some trouble getting a postgres query to work within some php that I am running. Essentially I am creating a daily report that will be emailed to a distribution list, but I can’t get my data to pull into the csv. This is something I have not done before so I’ve been using another similar report to get it this far. Can someone please help?

include('/some_connection/db_connect.inc');

ob_flush();

$yesterday_db = date('Y-m-d', strtotime('-1 days'));
$yesterday_msg = date('m/d/Y', strtotime('-1 days'));
$yesterday_fn = date('Ymd', strtotime('-1 days'));

$filename = 'fileData_'.$yesterday_fn.'.csv';

$path = '/tmp/';


$res = $db->getAll("SELECT tickets.order_number, tickets.customer_id, tickets.ticket_id, customers.email, (customers.first_name || ' ' || customers.last_name), customers.address_line_1, customers.address_line_2, customers.city, customers.state, customers.zip, (customers.first_name || ' ' || customers.last_name), customers.address_line_1, customers.address_line_2, customers.city, customers.state, customers.zip, customers.phone_1, customers.phone_2, customers.phone_3, contacts.notes
        FROM tickets, customers, contacts
        WHERE tickets.initial_call_date >= '$yesterday_db'
        AND tickets.initial_call_date <= '$yesterday_db'
        AND tickets.customer_id = customers.customer_id
        AND tickets.ticket_id = contacts.ticket_id");


$db2 = DB::connect('database');
$db2->setFetchMode(DB_FETCHMODE_ASSOC);

$handle = fopen($path.$filename,'w');

if(DB::isError($res)) { echo $res->getdebuginfo(); return;}
fwrite($handle,'"Account","Customer Code","Email","Bill Name","Bill Address 1","Bill Address 2","Bill City","Bill State","Bill Zip","Ship Name","Ship Address 1","Ship Address 2","Ship City","Ship State","Ship Zip","Phone 1","Phone 2","Phone 3","Description"'."\n");

foreach($res as $crow){
$id = $crow['customer_id'];
$res = $db->query("SELECT tickets.order_number, tickets.customer_id, tickets.ticket_id, customers.email, (customers.first_name || ' ' || customers.last_name) as bill_name, customers.address_line_1, customers.address_line_2, customers.city, customers.state, customers.zip, (customers.first_name || ' ' || customers.last_name) as ship_name, customers.address_line_1, customers.address_line_2, customers.city, customers.state, customers.zip, customers.phone_1, customers.phone_2, customers.phone_3, contacts.notes
        FROM tickets, customers, contacts
        WHERE tickets.initial_call_date >= '$yesterday_db'
        AND tickets.initial_call_date <= '$yesterday_db'
        AND tickets.customer_id = customers.customer_id
        AND tickets.ticket_id = contacts.ticket_id");

if(DB::isError($res)) { echo 'Error getting information for '.$id.'.'.$res->getdebuginfo()."\n"; return; }

$row = $res->fetchrow();

if(!empty($row)){
fwrite($handle,'"","'.$row['order_number'].'","'.$row['customer_id'].'","'.$row['ticket_id'].'","'.$row['email'].'","'.$row['bill_name'].'","'.$row['address_line_1'].'","'.$row['address_line_2'].'","'.$row['city'].'","'.$row['state'].'","'.$row['zip'].'","'.$row['ship_name'].'","'.$row['address_line_1'].'","'.$row['address_line_2'].'","'.$row['city'].'","'.$row['state'].'","'.$row['zip'].'","'.$row['phone_1'].'","'.$row['phone_2'].'","'.$row['phone_3'].'","'.$row['notes']."\n");
    } 
}

fclose($handle);

$to = 'someone@somemail.com';
$from = 'system@somemail.com';
$from_name = 'Daily Upload';
$replyto = '';
$subject = 'CSV for '.$yesterday_msg."\n";
$message = 'Attached is the ticket data for '.$yesterday_msg."\n";



mail_attachment($filename,$path,$to,$from,$from_name,$replyto,$subject,$message);


function remove_non_numeric($string) {
return preg_replace('/\D/', '', $string);
}


function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: text/csv; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
if (mail($mailto, $subject, "", $header)) {
    echo "mail send ... OK"; // or use booleans here
} else {
    echo "mail send ... ERROR!";
}
}?>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T11:32:54+00:00Added an answer on June 17, 2026 at 11:32 am

    I am posting the final code so that it can help someone else if they should need it.

    <?php
    include('/home/ ... some connection ... /db_connect.inc');
    ini_set("auto_detect_line_endings", true);
    
    ob_flush();
    
    $yesterday_db = date('Y-m-d', strtotime('-1 days'));
    $yesterday_msg = date('m/d/Y', strtotime('-1 days'));
    $yesterday_fn = date('Ymd', strtotime('-1 days'));
    $today_db = date('Y-m-d', strtotime('today'));
    
    $qty = 1;
    $amt = 0;
    $status = "'Service'";
    
    
    $filename = 'dispatchTrack_'.$yesterday_fn.'.csv';
    $path = '/tmp/';
    
    $db2 = DB::connect('odbc://connection');
    $db2->setFetchMode(DB_FETCHMODE_ASSOC);
        if (!$db2) {
            die('Could not connect: ' . pg_last_error());
        }
    
    $handle = fopen($path.$filename,'w');
    
    
    $query = "SELECT distinct (wo.work_order_id || '-' || t.order_number) AS order_number, wo.customer, 
    (c.first_name || ' ' || c.last_name) as bill_name, 
    (c.address_line_1) as bill_address_1, (c.address_line_2) as bill_address_2, 
    (c.city) as bill_city, (c.state) as bill_state, (c.zip) as bill_zip, 
    (c.first_name || ' ' || c.last_name) as ship_name, 
    (c.address_line_1) as ship_address_1, (c.address_line_2) as ship_address_2, 
    (c.city) as ship_city, (c.state) as ship_state, (c.zip) as ship_zip, 
    (c.phone_1) as phone1, (c.phone_2) as phone2, (c.phone_3) as phone3, 
    c.email, (p.item_id) AS model, (ppi.display_name || ' - ' || p.item_description) AS description, $qty, $amt, $status, (wo.visit_date) AS delivery_date,
    (techs.dispatch_code) AS truck, (p.problem_description) AS order_detail 
    FROM work_orders AS wo, customers AS c, tickets AS t, techs, problems AS p
    JOIN pta_package_items AS ppi
    ON p.item_id = ppi.item_id
    WHERE c.customer_id IN (SELECT DISTINCT wo.customer
            FROM work_orders AS wo
            WHERE wo.date_created >= '$yesterday_db'
            AND wo.date_created < '$today_db')
    AND wo.customer = c.customer_id
    AND t.ticket_id = wo.ticket_id
    AND p.ticket_id = t.ticket_id
    AND techs.tech_id = wo.tech
    AND wo.status = 1
    ORDER BY order_number";
    
    $result = pg_query($query) or die ('Query failed: ' . pg_last_error());
    
    fputcsv($handle, array('Order Number','Customer Code','Bill Name','Bill Address1','Bill Address2','Bill City','Bill State','Bill Zip','Ship Name','Ship Address1','Ship Address2','Ship City','Ship State','Ship Zip','Phone1','Phone2','Phone3','Email','Model','Description','Quantity','Amount','Delivery Type','Delivery Date','Truck','Order Detail','Comment1','Comment2','Comment3'));
    
    while ($row = pg_fetch_row($result)) fputcsv($handle, $row, $delimeter = ',', $enclosure = '"');
    
    fclose($handle);
    

    … and the rest of the file is the same as it was. Thanks again for those who commented I really appreciate the help.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I writing a query within ms sql server 2005 and having some trouble getting
Having some trouble getting this query to work correctly. mysql_query(DELETE FROM `table` WHERE `id`
Having some trouble getting this to work... I basically want the report to look
I am having some trouble getting an eval within data.table in R to work
Having some trouble getting a screenscraper webservice up and running on a weblogic 10.3.3
Im having some trouble getting the syntax right. I have a movie clip that
I'm having some trouble getting binding to work with JQuery. <iframe id=wufooFormz7x3k1 height=281 allowtransparency=true
I'm having some trouble getting Stripe up and running in my Rails app. When
I am having some trouble getting Elmah to work with url routing in an
I am having some trouble getting Python IO redirected to a console that I've

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.