fputcsv not exporting database into csv - mysql

Not outputting anything in csv file. Please help!!
This print_r($list).
outputs everything in the database in the right format But when i try to put the into a csv file only one line gets outputted.
$sql = "select * from " . TABLE_ORDERS . "";
$result = $db->Execute($sql);
if ($result->RecordCount() > 0) {
while (!$result->EOF) {
$file_date = date("d_m_Y_G_i_s");
$filename = "../weight/weightExport_".$file_date .".csv";
$customers_Name = $result->fields['customers_name'];
$list = array($customers_Name);
//print_r($list)."<br/>";
$handle = fopen($filename, 'w+');
fputcsv($handle, array('Username'));
fputcsv($handle, $list);
fclose($handle);
$result->MoveNext();
}
}

Change $handle = fopen($filename, 'w+');
to $handle = fopen($filename, 'a+');
It's only one line, because w+ is doing a truncate on that file.
a+ is the append mode.

Related

column names not getting exported into csv but data does

everything seems to work in the following code as in it does download data from the table but the column names are not showing in the csv what is wrong?
$stmt = $db->prepare("select * from interviews");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$filename = "export.csv";
$f = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachement; filename="export.csv"');
header("Pragma: no-cache");
header("Expires: 0");
foreach ($rows as $line) {
fputcsv($f, $line);
}
fclose($f);
Thanks

overwrite existing data based on returned values

Trying to overwrite existing data based on returned values, just want to get 'location' to update to the new info coming from a CSV import. Have a duplicated table with Oldlocation (all set to DW for testing, so any changes can be seen) Seems like it should be simple....:
$file = "allinv.CSV";
if(($handle = fopen($file, "r")) !== FALSE)
{ fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE){
$num = count($data);
for ($c=0; $c < $num; $c++) {
$col[$c] = $data[$c];}
$col1 = $col[1];
$sql = "SELECT Oldlocation FROM invbkup WHERE VIN = '$col1'"; ///works fine, gets old location for each record
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);
$whl= $row['Oldlocation'];
$col8 = $col[73];
$query = "UPDATE allinv SET location = '$col8' WHERE $whl = 'DW' ";
echo $col1, $col8, $whl, "</br>";////can see all the info but get no changes in database.
$a= mysqli_query($con, $query);
}
fclose($handle);
}
Nevermind, it was a simple problem I fix by putting it in an if statement:
if($whl = 'DW'){
$query = "UPDATE allinv SET location = '$col8' WHERE VIN ='$col1'";
$a= mysqli_query($con, $query);}
sometimes you over complicate the problem yourself, take a break, drink some coffee and try not thinking so hard.

Excel Not Saved as Numeric Format (MySQL to Excel)

I have a script that allows me to convert a database from MySQL to Excel .xls format, It was a success,
here is the code
<?php
// DB TABLE Exporter
//
// How to use:
//
// Place this file in a safe place, edit the info just below here
// browse to the file, enjoy!
// CHANGE THIS STUFF FOR WHAT YOU NEED TO DO
$cdate = date("Y-m-d");
$dbhost = "localhost";
$dbuser = "-";
$dbpass = "-";
$dbname = "-";
$dbtable = "-";
$filename = "C:\xxx";
// END CHANGING STUFF
// first thing that we are going to do is make some functions for writing out
// and excel file. These functions do some hex writing and to be honest I got
// them from some where else but hey it works so I am not going to question it
// just reuse
// This one makes the beginning of the xls file
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
// This one makes the end of the xls file
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
// this will write text in the cell you specify
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
// make the connection an DB query
$dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
mysql_select_db( $dbname );
$q = "SELECT * FROM ".$dbtable." ";
$qr = mysql_query( $q ) or die( mysql_error() );
//start the object
ob_start();
// start the file
xlsBOF();
// these will be used for keeping things in order.
$col = 0;
$row = 0;
// This tells us that we are on the first row
$first = true;
while( $qrow = mysql_fetch_assoc( $qr ) )
{
// Ok we are on the first row
// lets make some headers of sorts
if( $first )
{
// di comment karena ini ngasih label tabelnya, sepertinya nggak butuh
//foreach( $qrow as $k => $v )
//{
// // take the key and make label
// // make it uppper case and replace _ with ' '
// xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
// $col++;
//}
// prepare for the first real data row
$col = 0;
$row = 0;//$row++; // nyoba
$first = false;
}
// go through the data
foreach( $qrow as $k => $v )
{
// write it out
xlsWriteLabel( $row, $col, $v );
$col++;
}
// reset col and goto next row
$col = 0;
$row++;
}
xlsEOF();
//write the contents of the object to a file
file_put_contents($filename, ob_get_clean());
?>
this code produced a .xls file. I used Matlab to read my .xls file through readxls function, but it didn't recognize the value inside the .xls file as a numeric data, so my script on matlab couldn't make a matrix from reading my xls file. I had to convert it manually inside excel, there were some pop-ups near the value that offers me to convert it into numbers
If your goal is to take data from MySQL and put it in Matlab it might be easier to directly connect to MySQL from Matlab rather than sending the data through the xls format.
http://www.mathworks.com/help/database/ug/database.fetch.html

how to check if a file already exists in database?

trying to check to see if the file already exist but it doesn't work LINE 6
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
if (file_exists($_FILES['userfile']['name']))
{
echo $_FILES['userfile"]["name'] . " already exists. ";
}else{
$fp= fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
//include 'library/config.php';
//include 'library/opendb.php';
$query = "INSERT INTO upload (name, size, type, content )
VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
//include 'library/closedb.php';
echo "<br>File $fileName uploaded<br>";
}
}
$_FILES['userfile"]["name']
Make sure your opening quotes match the closing ones. Example valid strings are "this" and 'this', for example.
echo $_FILES['userfile']['name'] . " already exists. ";
echo $_FILES["userfile"]["name"] . " already exists. ";
// etc.

Reading a XLSX sheet to feed a MySQL table using PHPExcel

I found the PHPExcel library brilliant to manipulate Excel files with PHP (read, write, and so on).
But nowhere in the documentation is explained how to read a XLSX worksheet to feed a MySQL table...
Sorry for this silly question, but i need it for my work and found no answer on the web.
A small example could be very helpful.
Thanks a lot.
UPDATED :
I precise my question :
The only part of code i found in the documentation that could help me is to read an Excel file and display it in a HTML table :
`require_once 'phpexcel/Classes/PHPExcel.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("edf/equipement.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
echo '<table border="1">' . "\n";
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
}
echo '</tr>' . "\n";
}
echo '</table>' . "\n";`
I know i can use the loop to feed my MySQL table, but i don't know how... I'm not aware in OOP...
Can somebody help me, please ?
Here is the code
$inputFileName = $upload_path . $filename;
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$rows = array();
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$rows[$col] = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
}
mysql_query("INSERT INTO upload (`item_number`,`qty_sold`,`cost_home`) VALUES ($rows[1],$rows[2],$rows[3])");
}
?>
I have tried mysql_query("INSERT INTO upload (col1,col2) VALUES ($rows[1],$rows[2])"); as well but didn't work. The table stays empty
The first for loops through rows, and the second one loops through columns.
So, there are plenty of solutions to your "problem".
You could, for example, populate an array and make an insert statement for each row.
As the following :
$rows = array();
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$rows[$col] = mysql_real_espace_string($objWorksheet->getCellByColumnAndRow($col, $row)->getValue());
}
mysql_query("INSERT INTO your_table (col1,col2) VALUES ($rows[1],$rows[2])");
}
Obviously, this code can be improved.