Page 1 of 1

Session Value Set to Initial value after operation

Posted: Tue Dec 20, 2011 4:55 pm
by homepagestore
I am running PHP 5.3 on a VPS server. I have a problem with two php files. One displays the form on the screen and the second one is called by the first to export rows to a CSV file. The user can choose the name of the output file and then click the Export button. I want to display the results of the export below the Export button. The number of rows and total number of bytes written. I am using Session variables for the counters.

In the 1st page, the one that displays the form and then calls the export function, there is a session start at the top of the page and the Echo commands below the submit button to display the results when the export is complete.
// start the session
session_start();

if (isset($_POST['export'])) {

echo "<div style='text-align: left; width: 300px;'>";
echo "Rows Exported Successfully: " . $_SESSION['rowcount'] . "<br>";
echo " Bytes Written Successfully: " . $_SESSION['byteswritten'] . "<br>";
echo " Export Errors: " . $_SESSION['exporterrors'];
echo "</div>";
}
Print_r ($_SESSION);

In the page that performs the export, I have a session start and the instructions that initialize and increment the session variables.

// start the session
session_start();
// Initialize variables in the session
$_SESSION['exporterrors']='None';
$_SESSION['rowcount']=0;
$_SESSION['byteswritten']=0;

$putresult=fputcsv($file, array_keys($row));
if ($putresult == false) {
$_SESSION['exporterrors']='EXPORT: Error occurred writting row!<br>';
} else {
$_SESSION['byteswritten']=$_SESSION['byteswritten']+$putresult; // increment by bytes written
}

At the end of this page, a record is written to a table with the results. The correct results are recorded everytime.

The problem I have is after the first time I click the Export button, the totals on the page appear as the initial values. Each successive click of the Export button results in the correct totals being displayed.

The totals do not appear the first time the page is displayed.

Any idea why the totals are correct the second time and every time there after?

Thanks Ahead of time for your help...

Re: Session Value Set to Initial value after operation

Posted: Tue Dec 20, 2011 7:55 pm
by social_experiment
Could you attach the code (all files) to the post

Re: Session Value Set to Initial value after operation

Posted: Tue Dec 20, 2011 9:28 pm
by homepagestore
This is the file that displays the form, includes the export file and then displays the results after the export button is clicked.
<?php

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
if (!defined('W2P_BASE_DIR')) {
die('You should not access this file directly.');
}
//
// start the session
session_start();
?>
<form id="exportFrm" name="exportFrm" action="?m=ExportImport" method="POST" accept-charset="utf-8" >
<!-- <input type="hidden" name="dosql" value="do_Export_aed" />-->
<table width="100%" border="0" cellpadding="5" style="background: #fff;">
<tr>
<td>
<table border="0">

<tr>
<td nowrap="nowrap" colspan="3"><?php echo $AppUI->_('Export file name'); ?>: <input type="text" name="export_file_name" id="export_file_name"value="<?php echo "Access_Exported"."_".date(Y)."_".date(m)."_".date(d); ?>" size="50" class="text" />
</td>

</tr>
<tr>

<td colspan="3"><input type="submit" name="export" id="export" value="Export" class="button"/></td>
</tr>
<tr>
<td colspan="3" align="center"><br /><b><a href="<?php echo $baseUrl; ?>index.php?m=files&tab=4">Manage All Export files</a></b></td>
</tr>
<tr>
<td colspan="3">
<br> <?php
if (isset($_POST['export'])) {
echo "<table width=\"600\" border=\"0\" cellpadding=\"3\">";
echo "<tr><td colspan=\"2\" align=\"center\"><b>Export Results</b></td><td width=\"50%\"/></td></tr>";
echo "<tr><td align=\"right\">Rows Exported Successfully:</td><td align=\"left\"> " . number_format($_SESSION['rowcount']) . "</td><td></td></tr>";
echo "<tr><td align=\"right\">Bytes Written Successfully:</td><td align=\"left\"> " . number_format($_SESSION['byteswritten']/1024) . "KB</td><td></td></tr>";
echo "<tr><td align=\"right\">Export Errors:</td><td colspan=\"2\" align=\"left\"> " . $_SESSION['exporterrors'] . "</td></tr>";
echo "<tr><td colspan=\"2\" align=\"right\">&nbsp;</td><td align=\"right\">&nbsp;</td></tr>";
echo "<tr><td colspan=\"3\" align=\"center\"><b>Download: <a href=\"" . $_SESSION['exportfile'] . "\">" . $_SESSION['filename'] . "</a></b></td></tr>";
// fileviewer.php?file_id=97
echo "</table>";
// this clears variables in the session
$_SESSION['exporterrors']='None';
$_SESSION['rowcount']=0;
$_SESSION['byteswritten']=0;
$_SESSION['exportfile']='';
$_SESSION['filename']='';
}
// Print_r ($_SESSION);
?> <br>

</td>
</tr>
<tr><td colspan="3"></td></tr>
</table>
</td>
</tr>
</table>
<?php

if($_POST['export_file_name']!=null)
{
//echo($result);
// echo (' <a href='. $baseDir.'"files/0/'.$_POST['export_file_name'].'.csv" >download</a>');
}
?>

</form>

<?php include(W2P_BASE_DIR . '/modules/ExportImport/do_Export_aed.php'); ?>

Re: Session Value Set to Initial value after operation

Posted: Tue Dec 20, 2011 9:33 pm
by homepagestore
This is the file that performs the export and increments the session variables.
<?php

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
if (!defined('W2P_BASE_DIR')) {
die('You should not access this file directly.');
}
// start the session
// session_start();
?>

<?php
$con = mysql_connect($w2Pconfig['dbhost'],$w2Pconfig['dbuser'],$w2Pconfig['dbpass']);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if($_POST['export_file_name']!=null)
{
$exortnamefile=$_POST['export_file_name']; /*-----------------File name ---------------*/
$userowner=$AppUI->user_id;
$date=date("Y-m-d H:i:s");
$fileproject=rand(1, 100);
$number=date(mt_rand(1000, 100000));
$string=substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',5)),0,5);
$hexa=base_convert(mt_rand(0x1D39D3E06400000, 0x41C21CB8E0FFFFFF), 10, 36);
$random=$string.$number.$hexa;
mysql_select_db($w2Pconfig['dbname'], $con);

$project=mysql_query("SELECT prj.project_short_name as 'Project Number',
prj.project_name as 'Project Name',' ' as blank1,' ' as blank2,' ' as blank3, ypd.project_eab_number as EAB,
concat(ypd.project_address1,',',ypd.project_address2) as 'Project Address',
concat(ypd.project_city,',',ypd.project_state) as 'City And State',ypd.project_zip as 'ZIP Code',
if(pct.option='owner' or pct.option='owner agent',contacts.contact_first_name,'') as 'Owners First',
if(pct.option='owner' or pct.option='owner agent',contacts.contact_last_name,'') as 'Owners Last',
if(pct.option='owner' or pct.option='owner agent',cmp.company_name,'') as 'Owners Company',
if(pct.option='owner' or pct.option='owner agent',concat(cmp.company_address1,';',cmp.company_address2) ,'') as 'Owners Address',
if(pct.option='owner' or pct.option='owner agent',concat(cmp.company_city,',',cmp.company_state) ,'') as 'Owners City and State',
if(pct.option='owner' or pct.option='owner agent',company_zip,'') as 'Owners Zip','' as blank4,
if(pct.option='Design Professional' ,contacts.contact_first_name,'') as 'Design Professionals First',
if(pct.option='Design Professional' ,contacts.contact_last_name,'') as 'Design Professionals Last',
if(pct.option='Design Professional' ,cmp.company_name,'') as 'Design Professionals Company',
if(pct.option='Design Professional',concat(cmp.company_address1,',',cmp.company_address2) ,'') as 'Design Professionals Address',
if(pct.option='Design Professional' ,concat(cmp.company_city,',',cmp.company_state) ,'') as 'Design Professionals City and State',
if(pct.option='Design Professional' ,company_zip,'') as 'Design Professionals Zip',' ' as blank5,
if(pct.option='Alternate' ,contacts.contact_first_name,'') as 'Alternates First',
if(pct.option='Alternate' ,contacts.contact_last_name,'') as 'Alternates Last',
if(pct.option='Alternate' ,cmp.company_name,'') as 'Alternates Company',
if(pct.option='Alternate',concat(cmp.company_address1,',',cmp.company_address2) ,'') as 'Alternates Address',
if(pct.option='Alternate' ,concat(cmp.company_city,',',cmp.company_state) ,'') as 'Alternates City and State',
if(pct.option='Alternate' ,company_zip,'') as 'Alternates Zip',
' ' as blank6 ,' ' as blank7,' ' as blank8,' ' as blank9,
ypd.project_estimated_cost as 'project cost',
yacc.acct_plan_review_fee as 'Plan Review Fee',
yacc.acct_inspection_fee as 'Inspection Fee',
' ' as blank10,' ' as blank11,' ' as blank12,' ' as blank13,' ' as blank14,
yact.activity_plan_review_date as 'Plan Review Performed',
ypd.project_plan_drawing_date as 'Plan Date',
yact.activity_inspection_date as 'Inspection Date',
prj.project_description as 'Project Description'

from projects prj

LEFT JOIN yoda_project_details ypd on prj.project_id = ypd.project_details_project_id
LEFT JOIN yoda_project_contacts ypc on prj.project_id= ypc.project_contacts_project_id
LEFT JOIN contacts ON ypc.project_contacts_contact_id=contacts.contact_id
LEFT JOIN yoda_form_field_options pct ON ypc.project_contacts_type_id=pct.oid
LEFT JOIN companies cmp ON ypc.project_contacts_company_id=cmp.company_id
LEFT JOIN yoda_activity yact ON prj.project_id=yact.activity_project_id
LEFT JOIN yoda_accounting yacc ON prj.project_id=yacc.acct_project_id ");
$output = "";
$headers_printed = false;
$realfilename=uniqid(rand());
$warningresult=false;

$file = fopen("files/0/$realfilename","w");


// output header row (if at least one row exists)
$row = mysql_fetch_assoc($project);
$putresult=false;
if($row) {
$file = fopen("files/0/$realfilename","w");
$putresult=fputcsv($file, array_keys($row));
if ($putresult == false) {
$_SESSION['exporterrors']="Error occurred writing header row!<br>";
} else {
$_SESSION['byteswritten']=$_SESSION['byteswritten']+$putresult; // increment by bytes written
}
// reset pointer back to beginning
mysql_data_seek($project, 0);
}
while($row = mysql_fetch_assoc($project)) {
$putresult=fputcsv($file, $row);
if ($putresult == false) {
$_SESSION['exporterrors']=$_SESSION['exporterrors'] . 'Error occurred writing row ' . $_SESSION['rowcount']+1 . '<br>';
$_SESSION['exporterrors']=$_SESSION['exporterrors'] . 'Export Terminiated at row ' . $_SESSION['rowcount']+1 . '<br>';
break;
} else {
$_SESSION['byteswritten']=$_SESSION['byteswritten']+$putresult; // increment by bytes written
$_SESSION['rowcount']++;
}
}
fclose($file);
$selectmaxid=mysql_query("SELECT MAX(file_version_id) FROM files");


while ($row = mysql_fetch_array($selectmaxid)) {
$maxid=$row['MAX(file_version_id)'];
$maxid++;
}
$byteswritten=$_SESSION['byteswritten'];
$rowcount=$_SESSION['rowcount'];
$query ="INSERT INTO `files`(`file_real_filename`, `file_project`, `file_task`, `file_name`, `file_parent`, `file_description`, `file_type`, `file_owner`, `file_date`, `file_size`, `file_version`, `file_icon`, `file_category`, `file_checkout`, `file_co_reason`, `file_version_id`, `file_folder`, `file_helpdesk_item`, `file_indexed`) VALUES
('$realfilename', 0, 0, '$exortnamefile.csv', 0, '', 'application/csv', '$userowner','$date', '$byteswritten','$rowcount', 'obj/', 3, '', '', $maxid, 3, 0, 0);";
$result = mysql_query($query);
if ($result=false) {
$_SESSION['exporterrors']=$_SESSION['exporterrors'] . 'Error posting file (' . mysql_error() . ')<br>';
} else {
$query ="SELECT file_id FROM files WHERE file_real_filename='" . $realfilename . "';";
$result = mysql_query($query);
if (!$result) {
$_SESSION['exporterrors']=$_SESSION['exporterrors'] . 'Error posting file (' . mysql_error() . ')<br>';
} else {
$row=mysql_fetch_array($result);
$_SESSION['exportfile']="./fileviewer.php?file_id=" . $row['file_id'];
$_SESSION['filename']=$exortnamefile . ".csv";
}
}
mssql_close($db);
return $result;
}
?>

Re: Session Value Set to Initial value after operation

Posted: Tue Dec 20, 2011 9:44 pm
by homepagestore
I found a solution. I moved the initialize instructions from the second file to the first file and placed them after the results are displayed. Now it works every time. I would still like to know why the values come in as initial values the first time.

Re: Session Value Set to Initial value after operation

Posted: Fri Dec 23, 2011 3:58 pm
by homepagestore
The problem is back. It seemed to work, but today the first time I run the export the initial values are displayed. Everytime after the correct values are displayed.

I have update the code in the first two examples to show the current code. You can see where I initialize the counters after the results are displayed. I also removed the session start from the included file because I thought that might causing the problem since the second file is included and not called.

Any ideas what is causing this?