Community,
I am currently working on a report builder. The objective of the report builder is to send out an email with an excel document with weekly information coming from an sql table. It is activated when the first person logs in for the day on Monday. If Monday is a holiday, and no one logs in that day, a timestamp will not be made in the database. When the user logs in Tuesday, it looks at the last timestamp to see if one was placed for the previous day. if not, it will fire on tuesday.
The first step in this process looks like this...
$today = cal_to_jd(CAL_GREGORIAN,date("m"),date("d"),date("Y"));
$yesterday = date('Y-m-d', strtotime($date .' -1 day'));
$holiday = false;
if(jddayofweek($today,1) == 'Tuesday')
{
if(mysql_num_rows(mysql_query("select report_date from report_builder where report_date = '{$yesterday}'")) == 0)
{
$holiday = true;
}
}
if(jddayofweek($today,1) == 'Monday' || $holiday === true)
{
$today = mysql_query("select report_date from report_builder where report_date = CURDATE()");
if(mysql_num_rows($today) == 0)
{
$date = date('Y-m-d H:i:s',time()-(7*86400));
mysql_query("INSERT into report_builder (report_date) VALUES (CURDATE())");
//More code here
**The question for this particular post is as follows:
Is it possible to send the information to a csv file that does not actually open so the user can see, but instead be saved to a temporary file? Can this be done in a way where it doesn't send the background html?**
Once this is accomplished, I wanted to send the file to a user using my current code that looks like this...
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = "**********";
$mail->AddAddress("*************");
$mail->Subject = "Test";
$mail->Body = "HI";
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileName = addslashes($fileName);
echo $fileName;
$mail->AddAttachment("temporary file path");
if(!$mail->Send())
{
echo 'Message was not sent.';
echo 'Mailer error:'.$mail->ErrorInfo;
}
Yes you can certainly write a files to disk and save it in any number of ways. I will however point you to something that might be a quick way to save some steps (i.e. not have to create a file in PHP) if you application server and your MySQL are on the same physical host. This is of course assuming that a CSV file would be suitable (i.e. you don't actually need to use a PHP Excel library to build an XLS or XLSX file)
SELECT [fields] INTO OUTFILE '/path/to/file'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM your_table;
This will directly create a CSV at location path/to/file on the machine which can then be sent via PHP. Please note that the file name must not be an existing file name as this approach will not allow you to overwrite an existing file.
If your MySQL host is remote or you need to manipualte the data before writing to file, I would suggest looking at fputcsv() (http://php.net/manual/en/function.fputcsv.php) in order to write the data from your query directly to a file in CSV format.
$file = fopen('/path/to/file.csv', 'w');
while ($row = [YOUR DATABASE FETCH HERE]) {
fputcsv($file, $row);
}
Related
I am trying to add the date to a file which is emailed using SMTP in php. What i need is to add the date to the file name sent in the email, without changing the file name on the server. So my code still looks for 'file.csv' but names it '(date)file.csv' in the email attachment.
$mail->addAttachment('file.csv');
I have already tried.
$today = date("Y-m-d");
$filename = 'file'.$today.'csv'
$mail->addAttachment('./'.$filename, 'file.csv', 'base64', 'text/csv');
--solution--
$today = date("Y-m-d");
$filename = "file.csv";
$filename2 = 'file'.$today.'csv';
$mail->addAttachment($filename, $filename2);
It's not quite a duplicate as you know how to set both names, but you've simply got your filenames the wrong way around. Try this:
$today = date("Y-m-d");
$filename = 'file'.$today.'csv'
$mail->addAttachment('./file.csv', $filename, 'base64', 'text/csv');
The docs on this method are here.
I have written the script of sending automatic e-mail for a given date. I have already set up the cron job to execute this once a day for a given time. But it is not working. Can anyone show me the error here. I'm really new to this.
What I'm really supposed to do is to send an automatic email to a user on their birthday
<?php
$host="mysql117.000webhost.com/";//hostname
$username="abc";//mysql_username
$password="123";//mysql_password
$dbname="abc";//Database name
$tbl_name="customer_info";//table name
$date = date("2005-09-23"); //here my date format in my DB is 2010-09-30
$link = mysqli_connect('$host','$username','$password','$dbname');
if($link && mysqli_select_db('$dbname', $link))
{
$grabBday = "SELECT b_day,DATE_FORMAT(b_day,'2015-%m-%d') FROM customer_info where b_day = '2002-09-24'";
//here it will take the name of the person whose bday is on a particular date,I just hard coded this date to check if this is working
if($rs = mysqli_query($link, $grabBday))
{
while(mysqli_fetch_array($rs))
{
mail('abc92#yahoo.com', 'HAPPY BIRTHDAY', 'Many Happy Returns of the day');
}
}
} ?>
I am seeing logical difference as you are searching where b_day=$date where $date='2015-09-23' but dob can be '2002-09-23' or '1997-09-23' etc. so you will not get desired output, so you can change your query as per below if everything other than it is fine.
SELECT * FROM
tbl_name
WHERE CONCAT(YEAR(CURDATE()),DATE_FORMAT(b_day,'-%m-%d')) = $date
My project requires external CSV files to be uploaded to a database every week and required outputs are extracted whenever required. Currently am using the below to browse through a HTML form and upload to the table. It works fine!
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000,",")) !==false)
{
$placement_name = $fileop[2];
$statistics_date = $fileop[0];
$impressions = $fileop[5];
$clicks = $fileop[6];
$sql = mysql_query("INSERT INTO 'table'(source,advertiser,campaign,placement_name,statistics_date,impressions,clicks) VALUES ('xxx','yyy','zzz','$placement_name','$statistics_date','$impressions',' $clicks')");}
But now, we might need to do this on a daily basis and automated (which we hope to do with scheduled cron jobs), so decision was to use LOAD DATA LOCAL INFILE. As you could see the values inserted for source, advertiser and campaign are custom ones. How could we use the LOAD DATA... instead of the browse function?
In one of my application, users can upload CSV file (| separated fields), after uploading I am storing all the content of file in temporary table (I truncate this table every time for new upload so that it contains the current file data). After that I am iterating over each and every row of that table, and performs some database operation as per the business logic.
The following code will illustrate this:
if(isset($_POST['btn_uploadcsv']))
{
$filename = $_FILES["csvupload"]["name"];
$uploads_dir = 'csvs'; //csv files...
$tmp_name = $_FILES["csvupload"]["tmp_name"];
$name = time();
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$csvpath = "$uploads_dir/$name";
$row = 0;
$emptysql = "TRUNCATE TABLE `temp`";
$connector->query($emptysql);
if (($handle = fopen($csvpath, "r")) !== FALSE) {
$str_ins = "";
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
/*
* Here I am getting the column values to be store in the
* the table, using INSERT command
*/
unset($data);
}
fclose($handle);
}
/*Here I am selecting above stored data using SELECT statement */
for($j=0;$j<count($allrecords);$j++)
{
echo "In the loop";
/*If I use echo statement for debugging it is working fine*/
//set_time_limit(300);
/* I have tried this also but it is not working*/
if(!empty($allrecords[$j]['catid']))
{
// Here is my business logic which mailny deals with
// conditional DB operation
}
echo "Iteration done.";
/*If I use echo statement for debugging it is working fine*/
}
}
The problem is when I execute aboe script on server it is giving server timeout error. But when I test above script on my localhost, is is working fine.
Also as mentioned in the code, if I use echo statements for debugging, then it is working fine, and when I remove that it starts giving connection timeout problem.
I have tried set_time_limit(300), set_time_limit(0), but none of them seems to work.
Any idea, how can I resolve the above problem.
-- Many thanks for your time.
Edit:
I have checked that, files are uploading on the server.
set_time_limit
change to
ini_set("max_execution_time",300);
When max_execution_time is not set in php.ini set_time_limit valid.
I have resolved the issue using flush, to send intermediate output to the browser, while the query is executing in the background.
This is how I modified the code:
for($j=0;$j<count($allrecords);$j++)
{
/*At the end of each iteration, I have added the following code*/
echo " ";
flush();
}
Thanks to the contributors over this link PHP: Possible to trickle-output to browser while waiting for database query to execute?, from where I got inspiration.
I am trying to create a php script that will be run by a cron job on a nightly basis.
The database holds entries from a contact form.
The idea is to run the php script (via cron) and have it export any new entries from the database from that day into a csv file on the server, overwriting that file each time for housekeeping. It needs to only export the entries to the database from that day.
Here is what I have at the moment:
<?php
// Connect and query the database for the users
$conn = new PDO("mysql:host=localhost;dbname=dbname", 'username', 'password');
$sql = "SELECT * FROM enquiries ORDER BY firstname";
$results = $conn->query($sql);
// Pick a filename and destination directory for the file
// Remember that the folder where you want to write the file has to be writable
//$filename = "/tmp/db_user_export_".time().".csv";
$filename = "/home/domain/public_html/csv/db_user_export.csv";
// Actually create the file
// The w+ parameter will wipe out and overwrite any existing file with the same name
$handle = fopen($filename, 'wb');
// Write the spreadsheet column titles / labels
fputcsv($handle, array('FirstName','Email'));
// Write all the user records to the spreadsheet
foreach($results as $row)
{
fputcsv($handle, array($row['firstname'], $row['email']));
}
// Finish writing the file
fclose($handle);
?>
Your sql must by:
SELECT * FROM enquiries where DATE(DateField) = CURDATE() ORDER BY firstname