Using fgetcsv and fopen issue with looping never exiting - php

There's an issue with this piece of code it never gets to the "Done" echo.
for($current_day=1;$current_day<=10;$current_day++){
echo("lists/Day ".$current_day.".csv </br>");
$person_data = "";
if ( ( $handle = fopen( "lists/Day ".$current_day.".csv", "r" ) ) !== FALSE ) {
while ( ( $data = fgetcsv( $handle, 1000, ",", "//" ) ) !== FALSE ) {
if ( $data[2]!="Grade" ) {
$collection = $db->students;
$person_data['last_name'] = trim( $data[0] );
$person_data['first_name'] = trim( $data[1] );
$person_data['fullname'] = $person_data['first_name'].' '.$person_data['last_name'];
//var_dump($person_data);
$cursor = $collection->findOne(array('fullname'=>$person_data['first_name'].' '.$person_data['last_name']));
if($cursor!=null){
echo("UPDATE");
if($cursor['frees'][$current_day-1] != 1){
$cursor['frees'][$current_day-1] = 1;
echo 'Updated: '.$data[0] . " - ". $data[1] . " - ". $data[2] . "</br>" ;
$collection->save($cursor);
}
}
else{
echo("ADD");
//addperson($data,$current_day);
}
}
// do something with the data here
//echo $data[0] . " - ". $data[1] . " - ". $data[2] . "</br>" ;
}
fclose( $handle );
echo("Done");
}
else{
echo "FALSE";
}
}
outputs
1
lists/Day 1.csv
ADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADD
Which is correct but never loops to the second csv

Related

ERROR: In exporting mysqli query results into excel using php

I am trying to export MySQL query results into excel. Therefore I wrote the following PHP script:
<?php
$conn = mysqli_connect('localhost','root','xyz','abc');
$select = "SELECT * FROM table_name";
$export = mysqli_query( $conn,$select) or die ( "Sql error : " .
mysqli_error($conn) );
$fields = mysqli_num_rows ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
//But this line giving error continuously
$header .= mysqli_fetch_field_direct($export,$i) . "\t";
}
while( $row = mysqli_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=random.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
But I am getting this error:
PHP Recoverable fatal error:
Object of class stdClass could not be converted to string in this line
$header .= mysqli_fetch_field_direct($export,$i) . "\t";
and now I'm facing problem in debugging this code.
Look to description and examples.
This mysqli_fetch_field_direct returns an object
Or try typecasting : (string)mysqli_fetch_field_direct($export,$i)
http://php.net/manual/en/mysqli-result.fetch-field-direct.php
I found the solution for my problem,instead of doing this $header .= mysqli_fetch_field_direct($export,$i) . "\t"; now i am using $header .= mysqli_fetch_field_direct($export,$i)->name . "\t";.
Now Its working fine.

Change Export File Type

I have this script that allows me to save a mysql database table as a excel spreadsheet from a php webpage. But it needs to be saved as a PDF. I have looked around and cant find any fix to my code.
<?php
include "db.php";
$SQL = "Select Name, Email, Department, Cellphone, Extension from contacts";
$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=Telephone List.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$result";
?>

I have some record in mysql database .I want to export daily record in csv file format using php?

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

Export to csv after printing table in mysql

Been trying to figure this out since a hell of a lot of hours, but without result. A user can select some filters in a form, which result in a unique table, printed to the screen.
Then I want a button to export this specific table to a csv file, stored on the users computer.
if(isset($_POST["askReport"])){
//all the variables
//...
$myQuery = ""SELECT *, TIME_TO_SEC(stopwerkdagU) - TIME_TO_SEC(startwerkdagU) - pauzetijdU AS totaalurenU, TIME_TO_SEC(stopwerkdagU) - TIME_TO_SEC(startwerkdag) - pauzetijd AS totaaluren FROM `newRegister` $u $aP $pD $uF $sD"";
$result = $mysqli->query($myQuery);
if($result->num_rows >0){
print '<table><tr><th>.....'; //and all the headers
print '<td>'.$row["user"].'</td>';
..... //and all the other columns and end of row
}
So far, so good, I get a nice table with the results that I want. But then comes the tricky part - how do I get the button to download this table? Here's what I tried: (this code is stil in the isset($_POST["askReport"]) if statement)
// DOWNLOAD TABEL
print '<form method="POST"><button name=download>download</button></form>';
if(isset($_POST["download"])){
$select = "SELECT *, TIME_TO_SEC(stopwerkdagU) - TIME_TO_SEC(startwerkdagU) - pauzetijdU AS totaalurenU, TIME_TO_SEC(stopwerkdagU) - TIME_TO_SEC(startwerkdag) - pauzetijd AS totaaluren FROM `newRegister` $u $aP $pD $uF $sD";
$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=download .xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
};
}
This doesn't give any errors. It just reloads the page. So I can't figure out why it isn't working. I thank you for your help.
PARTIAL SOLUTION
The following code (your code, just with the MySQL commented out for testing purposes) works fine. I'm running Apache/2.4.9 (Unix) PHP/5.5.14
The thing that made the downloading work was when I put the <?php and ?> tags in. Try this code and let me know if it works.
<?php
// DOWNLOAD TABEL
print '<form method="POST"><button name=download>download</button></form>';
if(isset($_POST["download"])){
$select = "SELECT *, TIME_TO_SEC(stopwerkdagU) - TIME_TO_SEC(startwerkdagU) - pauzetijdU AS totaalurenU, TIME_TO_SEC(stopwerkdagU) - TIME_TO_SEC(startwerkdag) - pauzetijd AS totaaluren FROM `newRegister` $u $aP $pD $uF $sD";
/* $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="abc,123";
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=download .xls");
header("Pragma: no-cache");
header("Expires: 0");
echo "$header\n$data";
};
?>

Convert Database to CSV and Save file to folder on server

I've have been successful in exporting my database to csv as a downloadable file. However what I now need to do is instead of creating a straight .csv file that's downloaded I need it to just save to a folder called "csv" on the server. Here is my code for the current export. I need help in the saving to the server part. CHMOD on the folder (csv) is 777
$today = date('Y-m-d');
$select = "SELECT * FROM goldpacks WHERE date = '$today'";
$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=import.csv");
print "$header\n$data";
All you need to add is a call to file_put_contents(). You already have your csv correctly formatted in $data so the write process is simple:
// $filename is whatever you need the file to be called
file_put_contents("/path/to/csv/" . $filename, "$header\n$data");
Rather than 777 permissions on the csv folder, it should be owned by user the web server runs as with 700, or group-owned by the web server user as 770.

Categories