Here is my situation.
I am sending records to database through php file. Then I have a date field being set with now(). It adds the date in this format: 2013-08-01
Then I am exporting the database to a csv. It all works fine. However, I need to take the dashes out when I am exporting it to the csv. So I need it to read: 20130801
Is there a way to do this? Here is my export to csv code:
$from = $_REQUEST['from'];
$to = $_REQUEST['to'];
$filename = "APGE_ELEC_" . $to;
header('Content-Disposition: attachment; filename="'.$filename.'".csv"');
$hostname = ""; //SET SERVER/HOSTNAME
$dbusername = ""; //SET DATABASE USERNAME
$dbname = ""; //SET DATABASE NAME
$dbpassword = ""; //SET DATABASE USERNAME
$dbhandle = mysql_connect($hostname, $dbusername, $dbpassword)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($dbname,$dbhandle)
or die("Could not select Data Base");
//$query = "SELECT * FROM v88374 WHERE ((date >= '$from') AND (date <= '$to'))";
$query = "SELECT * FROM v88374 WHERE date >= DATE_FORMAT('" . $from . "', '%Y%m%d') AND date <= DATE_FORMAT('" . $to . "', '%Y%m%d')";
//$query = "SELECT * FROM v88374 WHERE date >= DATE_FORMAT($from) AND date <= DATE_FORMAT($to)";
$export = mysql_query ($query ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) ."|" . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = $value . '|' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
print "$header\n$data";
exit();
The $to and $from are parameters for searching for date range in the database. So we can leave that alone.
You need to select the formatted time
$query = "SELECT *, DATE_FORMAT(date,"%Y%m%d") FROM v88374 WHERE date >= DATE_FORMAT('" . $from . "', '%Y%m%d') AND date <= DATE_FORMAT('" . $to . "', '%Y%m%d')";
SELECT DATE_FORMAT(datefield, '%Y%m%d')
if you want to do it directly in the database.
This problem can be easily tackled by taking advantage of the way MySQL processes the value in the Date field. Just add 0 and the dashes will be removed
select now();
//gives 2019-12-03 08:44:10
select now()+0;
//gives 20191203084504
You can process this integer as a string and get whatever parts of this are needed.
You could use str_replace() like you did for the quotes, but modify it for dashes, replacing them with empty strings.
$value = str_replace( '-' , '' , $value );
This poses some danger, though. What if you have other data types that use dashes? They'd be corrupted. Another option is to use explode() and checkdate() to make sure it's a date before you remove the dashes. Example:
$dt = explode("-", $value); // Yields array([0] => 2013, [1] => 08, [2] => 01)
// checkdate(int month, int day, int year)
if (checkdate($dt[1], $dt[2], $dt[0])) {
// It's a date.
$value = str_replace('-','',$value);
}
$newDate = str_replace('-', '', $oldDate)
Is that what you're looking for?
In addition php provides some awesome date formatting features: http://php.net/manual/en/function.date.php
$date="2013-08-01";
$converted_date=date("Ymd", strtotime($date));
I tend to prefer a more OOP approach. This way if you ever need to change the format, you can easily modify it.
$date = new DateTime($date_from_mysql);
echo $date->format('Ymd'); // Or adjust the format how you like
Of course, you shouldn't be using the deprecated ext/mysql extension for new projects anyway.
Related
I am using PHP to create an XML document from a database to import into Adobe InDesign. I want to be able to add a comma after each entry but not on the last one. I have tried using implode() but I have had no luck. Any help would be greatly appreciated. Here is the code with out any attempt at adding the comma. I can just add a comma after the closing but that will still give me one on the last entry. Any advice on how to attack this would be much appreciated. Thanks!
function getAssocXML ($company) {
$retVal = "";
// Connect to the database by creating a new mysqli object
require_once "DBconnect.php";
$staffResult = $mysql->query("
SELECT company,
fName,
lName,
title,
contact1,
contact2
FROM staff
WHERE company = '$company'
AND title
LIKE '%Associate%'
AND archive = 0
");
if ($staffResult->num_rows >= 1 && $staffResult->num_rows < 4) {
$retVal = $retVal;
for ($i = 0; $i < $staffResult->num_rows; $i++) {
// Move to row number $i in the result set.
$staffResult->data_seek($i);
// Get all the columns for the current row as an associative array -- we named it $aRow
$staffRow = $staffResult->fetch_assoc();
// Write a table row to the output containing information from the current database row.
$retVal = $retVal . "<staff>";
$retVal = $retVal . "<name>" . $staffRow['fName'] . " " . $staffRow['lName'] . "</name>";
$retVal = $retVal . "<contact>" . staffContact($staffRow['contact1'], $staffRow['contact2']) . "</contact>";
$retVal = $retVal . "</staff>";
}
$retVal = $retVal . " — Associate
";
$staffResult->free();
}
if ($staffResult->num_rows > 4) {
$retVal = $retVal;
$retVal = $retVal . "<staffHeader>Associates: </staffHeader>";
for ($i = 0; $i < $staffResult->num_rows; $i++) {
// Move to row number $i in the result set.
$staffResult->data_seek($i);
// Get all the columns for the current row as an associative array -- we named it $aRow
$staffRow = $staffResult->fetch_assoc();
// Write a table row to the output containing information from the current database row.
$retVal = $retVal . "<staff>";
$retVal = $retVal . "<name>" . $staffRow['fName'] . " " . $staffRow['lName'] . "</name>";
$retVal = $retVal . "<contact>" . staffContact($staffRow['contact1'], $staffRow['contact2']) . "</contact>";
$retVal = $retVal . "</staff>";
}
$retVal = $retVal . "
";
$staffResult->free();
}
return $retVal;
}
print getAssocXML(addslashes($aRow['company']));
You can do it with the help of this query
echo join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1)), 'strlen'));
OR
$last = array_slice($array, -1);
$first = implode(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last), 'strlen');
echo implode(' and ', $both);
I'm afraid that I don't readily grasp your intent here. I don't see anything in your code that is using any sort of array, which is a pre-requisite for implode() (a.k.a. join())
However, here's a little trick that I've used numerous times when I am building something in a loop:
$result = "";
$comma = "";
foreach (...) {
.. calculate some $value ..
$result = $result . $comma . $value;
$comma = ",";
}
The first time through the loop, $comma isn't a comma! It's an empty string. At the end of the first iteration through the loop, it becomes a comma, for use next time. It's a simple but effective way to build an arbitrarily-long "comma-separated string" in-place.
HTH!
this is how i use mysql to get CSV export.If you have better code then suggest me
while( $row = mysql_fetch_row( $export ) ) {
$line = '';
foreach( $row as $value ) {
if ( ( !isset( $value ) ) || ( $value == "" ) ){
$value = ",";
}
else {
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . ",";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
$date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
}
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$file_name.".csv");
print "$header\n$data";
exit;
?>
Please give me the solution
PHP has a fputcsv function you can use for these purposes:
http://php.net/manual/en/function.fputcsv.php
I am running the sql as shown below to select all rows in my database which has the defined Interest Code. Now I'd like to export all the selected results into a CSV, but this is to happen about 30 times as there are about 30 interest codes. Is there a way for me to loop through 1 sql after another, each time creating a new CSV with the results of the new SQL query?
Example of two of the sql queries.
select * from subscribers where list=27 and custom_fields LIKE '%\%CV\%%';
select * from subscribers where list=27 and custom_fields LIKE '%\%JJC\%%';
and so on... Each time creating an entirely new CSV file. 30 files.
I've found the following (untested yet) but I suppose this would be the php but with the need for it to keep going through 1 sql after another.
$select = "select * from subscribers where list=27 and custom_fields LIKE '%\%CV\%%';";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
I'd write a function that creates a single export and then call that in a loop of the different codes. Something like this:
function export($code)
{
$query = "select * from subscribers where list=27 and custom_fields LIKE '%\%" . $code . "\%%'";
// put the results for this query in $data as in your example
file_put_contents('/path/to/file/for/code_' . $code, $data);
}
$codes = array('CV', 'JCC', '...');
foreach ($codes as $code) {
export($code);
}
How do i make the columns wider and the headers different other than the column name of the table in mysql? and how do i make it have a larger font? I am new to exporting excel files i have no idea how to do it, i've tried researching about it but i didn't understand it either. thank you in advance for your help.
Here is my export.php
<?php
require 'config.php';
$SQL = "SELECT prod_brand, prod_name, prod_category, prod_price, prod_desc, prod_quantity from inventory";
$header = '';
$result ='';
$exportData = mysql_query ($SQL ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $exportData );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $exportData , $i ) . "\t";
}
while( $row = mysql_fetch_row( $exportData ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$result .= trim( $line ) . "\n";
}
$result = str_replace( "\r" , "" , $result );
if ( $result == "" )
{
$result = "\nNo Record(s) Found!\n";
}
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename=InventoryExport'.date('m-d-Y H:i:s').'.xls');
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$result";
?>
See the PHP code sample from this link, where the headers names are custom and the rows are extracted from a database:
http://www.easyxls.com/manual/basics/export-list-to-excel.html
To increase the font size of the header use this code:
// Create an instance of the object used to format the cells
$xlsAutoFormat = new COM("EasyXLS.ExcelAutoFormat");
//Set the style of the header
$xlsHeaderStyle = new COM("EasyXLS.ExcelStyle");
$xlsHeaderStyle->setFontSize(18);
$xlsAutoFormat->setHeaderRowStyle($xlsHeaderStyle);
I am trying to implode some variables and insert them into a MySql database, but for some reason it is not working. I have been trying for hours and I''m just not sure what I'm doing wrong.
If you can help it would be much appreciated.
$AddressString = "address1,address2,address3,address5,postcode";
$AddressSplit = explode( ",", $AddressString ); //split the address string
$StringLength = count( $AddressSplit ) - 1;
$s = 0; //trim any white spaces from the address string
while ( $s < count( $AddressSplit ) ) {
$AddressSplit[$s] = trim( $AddressSplit[$s] );
$s++;
}
//Create the Values to insert into DB
$MysqlValues = implode( "','", $AddressSplit );
$MysqlValues = "'$MysqlValues'";
$NumberVals = count( $AddressSplit );
$t = 1;
while ( $t < $NumberVals ) {
$ad[$i] = "add$i";
$t++;
}
$TableNames = implode( ", ", $ad );
mysql_query( "INSERT INTO pstc_add_main (" . $TableNames . ",add10,date)
VALUES (" . $MysqlValues . ",'$cdate')" );
}
Because you start making the field names 1 based, your are one field short!
In the end you must end with a equal number of fields and values.
Try this:
$t = 0;
while ( $t < $NumberVals ) {
$ad[$i] = "add$i";
$t++;
}
Or, if you do not want the first field to be "add", change it like this:
$t = 1;
while ( $t <= $NumberVals ) {
$ad[$i] = "add$i";
$t++;
}
Of course, it would have been a easy test to do:
$sql = "INSERT INTO pstc_add_main (" . $TableNames . ",add10,date)
VALUES (" . $MysqlValues . ",'$cdate')";
var_dump($sql);
mysql_query($sql);
Not tested,
I doubt you change,
$MysqlValues = implode("','", $AddressSplit);
to
$MysqlValues = implode(",", $AddressSplit);
Just use
$MysqlValues = implode( ",", $AddressSplit );
and try to edit the code like
mysql_query( "INSERT INTO pstc_add_main (".$TableNames." ,add10,date)
VALUES (" . $MysqlValues . ",$cdate)" );