How to write array values into a csv file in PHP? - php

I have an array whose structure is like $data = array{0=>'abc',1=>xyz,2=>tqs}
Now I need to write these values into a csv file. I need to display every value in 1st column and with everytime new row on new insert along with previous value already available.
Below is the code I am using but everytime I execute it I get the last value in the file:
for ($c=0; $c < $num; $c++) {
echo $data[$c];
echo $query = "select prod_sku,prod_name
from
tbl_product
where
prod_sku = '".$data[$c]."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if(empty($row)){
print_r($row);
echo 'test';
$fp = fopen("file.csv", "w");
print_r($data[0]);
fputcsv($fp, $data[0]);
fclose($fp);
}
How can i achieve this using PHP?

The problem is that you are doing fopen inside the for loop, so every time the loop runs, your file gets re-written. Move the fopen and fclose outside of the loop and it will work. Like this;
$fp = fopen("file.csv", "w");
for ($c=0; $c < $num; $c++)
{
$query = "select prod_sku,prod_name from tbl_product where prod_sku = '".$data[$c]."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
fputcsv($fp, $data);
}
fclose($fp);

If you use MySQL you could use SELECT ... INTO OUTFILE:
SELECT prod_sku, prod_name
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM tbl_product
WHERE 1
http://dev.mysql.com/doc/refman/5.0/en/select.html

Related

while loop not looping with str_pad

Im currently trying to do a loop where it will display all the records in the table. but the result that i get now is it display one data which the last record from the table. what should i do if i want to make it display all the records in table and not only one data being display
$myFile = "testFile.txt";
$fo = fopen($myFile, 'w' ) or die ("cant open file");
$header = str_pad($rekod,0).str_pad($organisasi,5).str_pad($jabatan,40).str_pad($tarikh_kredit,8).str_pad($sec_code,16,"0").str_pad($filler,150)."\n";
$sql = "SELECT * FROM pengerusi_johor WHERE negeri='$negeri'";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($result))
{
$detail = str_pad($rekod,0).str_pad($bank_code,7).str_pad($row['nombor_akaun'],16).str_pad($row['nama'],40);
}
fwrite($fo,trim($header).PHP_EOL.$detail);
fclose($fo);
In your code you are overwriting the value of $detail each time round the loop with the value in while ..
you should use .= to append each row to your string
while($row = mysqli_fetch_array($result)) {
$detail .= str_pad($rekod,0).str_pad($bank_code,7).str_pad($row['nombor_akaun'],16).
str_pad($row['nama'],40);
}

Remove duplicates from PHP array (array_unique)

I am getting a specific field from 4 different tables.
<?php
//I connect to the database and the 4 tables
// Location of CSV
$location = 'path.csv';
// List creation that will be updated with the fields and be put into my CSV file
$list = array();
// Read csv file to avoid adding duplicates
$file = fopen($location, 'r');
$data = array();
while($row = fgetcsv($file))
{
$data[] = $row;
}
// Query 1
$sql = ('select distinct(field) as field from '.$table1.'');
// Run the query
$query = $Db->query($sql);
// Check for SQL errors
if ($Db->error)
{
return ($Db->error);
}
// Put data in the list
while ($row = $query->fetch_assoc())
{
array_push($list,array($row['field'], ''));
}
// Query 2
$sql = ('select distinct(field) as field from '.$table2.'');
// Run the query
$query = $Db->query($sql);
// Check for SQL errors
if ($Db->error)
{
return ($Db->error);
}
// Put data in the list
while ($row = $query->fetch_assoc())
{
array_push($list,array($row['field'], ''));
}
// Query 3
$sql = ('select distinct(field) as field from '.$table3.'');
// Run the query
$query = $Db->query($sql);
// Check for SQL errors
if ($Db->error)
{
return ($Db->error);
}
// Put data in the list
while ($row = $query->fetch_assoc())
{
array_push($list,array($row['field'], ''));
}
// Query 4
$sql = ('select distinct(field) as field from '.$table4.'');
// Run the query
$query = $Db->query($sql);
// Check for SQL errors
if ($Db->error)
{
return ($Db->error);
}
// Put data in the list
while ($row = $query->fetch_assoc())
{
array_push($list,array($row['field'], ''));
}
// Save list in the csv file without overwriting
$fp = fopen($location, 'a');
foreach (array_unique($list) as $fields)
{
if (in_array($fields, $data))
{
echo "Duplicate found";
}
else
{
echo "Save to file";
fputcsv($fp, $fields);
}
}
fclose($fp);
?>
In the end I check if the fields are already in the file. The only problem is that I still have duplicates because some tables might have exactly the same field. So, I want to remove the duplicates from the PHP array "list".
I am using :
$cleanlist = array_unique($list);
but I am getting an error:
PHP Notice: Array to string conversion
More specifically the change in my code is :
$cleanlist = array_unique($list);
// Save list in the csv file without overwriting
$fp = fopen($location, 'a');
foreach ($cleanlist as $fields)
{
if (in_array($fields, $data))
{
echo "Duplicate found";
}
else
{
echo "Save to file";
fputcsv($fp, $fields);
}
}
As explain in the docs, array_unique compares elements as strings by default. You are getting this error because PHP is trying to convert an Array to string. You have a 2D array, an array of array.
You can use the flag SORT_REGULAR to compare the elements as they are.
But be careful, only same key/value pairs are considered identicals.
You could reduce amount of code a lot by using UNION in SELECT statement.
SELECT field FROM table1
UNION
SELECT field FROM table2
UNION
SELECT field FROM table3
UNION
SELECT field FROM table4
UNION returns distinct results by default.
That worked :
$list = array_map("unserialize", array_unique(array_map("serialize", $list)));
The $list is a 2d array.

Exporting data from database to csv file using php

I am able to export database to csv but my code somehow imports twice the data to my csv file. I.e same column twice side by side.this is my code. I think my problem is with the implode statment. Any help would be appreciated.
<?php
$db = new sqlite3('I:\preethi\webbs.db');
$headers = array
('Id','CompanyId','DateTime','Serial','DeviceId','AgentAId','GpsAddress','Targa','CommonRoadDescription'
,'RoadCivicNumber','VehicleBrandDescription','VehicleModelDescription' ,'VerbaliVehicleTypeDescription','CommonColorVehicleDescription','VerbaliRuleOneCode','VerbaliRuleOneDes
cription','VerbaliRuleOnePoints'
,'VerbaliClosedNoteDescription','Points','VerbaliMissedNotificationDescription
','MissedNotificationNote','StatementNote');
$results = $db->query('select'.implode (',',$headers).'from VerbaliData');
//$results = $db->query( 'select
Id ,CompanyId ,DateTime ,Serial ,DeviceId ,AgentAId
,GpsAddress ,Targa ,CommonRoadDescription ,RoadCivicNumber ,VehicleBrandDescription
,VehicleModelDescription ,VerbaliVehicleTypeDescription ,CommonColorVehicleDescription
,VerbaliRuleOneCode ,VerbaliRuleOneDescription ,VerbaliRuleOnePoints ,VerbaliClosedNoteDescription
,Points ,VerbaliMissedNotificationDescription ,MissedNotificationNote ,StatementNote from
VerbaliData');
$fp = fopen('explores.csv', 'w');
fputcsv($fp,$headers);
while ($row = $results->fetchArray()) {
fputcsv($fp, $row);
}
fclose($fp);
?>
Just try with :
while($row = $results->fetchArray(SQLITE3_NUM)) {
Or
while($row = $results->fetchArray(SQLITE3_ASSOC)) {
More Details: http://php.net/manual/en/sqlite3result.fetcharray.php
You have a slight prob in your code fetchArray() returns two array sets one associative and one is numbered, use fetchArray(SQLITE3_NUM) or fetchArray(SQLITE3_ASSOC).

Iteration when uploading CSV file not able to print desired output

I have this code which I use in order to upload a CSV file.
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into matching(date, time, location, epos_id, rbpos_id, type_of_payment, basket_information, user_id, points) values('$data[0]', '$data[1]', '$data[2]', '$data[3]', '$data[4]', '$data[5]', '$data[6]', '$data[7]', '$data[8]')";
mysql_query($import) or die(mysql_error());
$query = 'SELECT * FROM users WHERE ID="'.$data[7].'"';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$id_user = $row['user_id'];
$phone = $row['phone'];
echo $name = $row['first_name'];
}
mysql_query($import) or die(mysql_error());
}
fclose($handle);
Now, I need to iterate each data on the column $data[7], so I echo the first name of each person who has that user_id, but apparently it's wrong because nothing is printed.
PS. please note that I'm the only one uploading the data, I'm not concerned about security stuff or whatever.
Done plenty PHP database stuff but not much with mysql. Would have thought the way you've written the select statement with double quotes surrounding the ID string should be the other way round? I.e. use double quotes for the query string enclosing single quotes for the ID value:
$query = "SELECT * FROM users WHERE ID='".$data[7]."'";
You might want to try some debugging - like putting print_r($row); into your while loop.
I am submitting sample code to read data from the csv file. I have assumed that you have written the precise code for uploading the csv file by using the move_uploaded_file command. So my sample code continues from that point.
// Set path to CSV file
$csvFile = 'test.csv';
$file_handle = fopen($csvFile, 'r');
//fgetcsv($file_handle);//skips the first line while reading the csv file, uncomment this line if you want to skip the first line in csv file
while (!feof($file_handle) )
{
$csv_data[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
/*echo '<pre>';
print_r($csv_data);
echo '</pre>';*/
foreach($csv_data as $data)
{
echo "<br>column 1 data = ".$data[0];
//Your insert will go something like this
$import="INSERT into matching(date, time, ..) values('".mysql_real_escape_string($data[0])."', '".mysql_real_escape_string($data[1])."',....)";
mysql_query($import) or die(mysql_error());
}
For demo only I have only printed the value of the first column only. If you want to know the complete structure of the data array you can do it by uncommenting the print_r block. The function mysql_real_escape_string will safely insert the csv data into the database table, if you don't use this function there is high possibility that your mysql query can fail if your csv data contains single or double quotes which breaks the query.

Writing a Database Query to a file

I am trying to write a Database Query to a file, But am just wondering how I get the SQL Data to be input into the file.
It is currently outputting nothing to the .txt file at all. I suspect its something to do with the while loop and am questioning whether it needs to be there or not.
My code is :
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);
$query = "SELECT gamename, username, MAX(thescore)
FROM game_scores
GROUP BY gamename, username
ORDER BY gamename, thescore DESC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$scoredata = $row;
}
//save file
$handle = fopen('scores/games-backup'.'.txt','w+');
fwrite($handle,$scoredate);
fclose($handle);
echo "Success";
}
Any help on writing the SQL Results to this text file would be much appreciated.
$row is an array, you will need to make it a string before you can write it to a file, you can use implode().
$scoredata is also being overwritten in each loop, maybe use $scoredata[] instead
while($row = mysql_fetch_array($result)) {
$scoredata[] = implode("; ", $row);
}
This will make $scoredata an array also, so you will need to convert that to a string too!
$handle = fopen('scores/games-backup'.'.txt','w+');
fwrite($handle,implode("\r\n", $scoredata));
fclose($handle);
This should print each database row on a new line in the file.
EDIT: This will just be a text file, formatted as text, not that great for a backup file. You will need to structure the text into an SQL format to make it useful..
Try something like :
$handle = fopen('scores/games-backup'.'.txt','w+');
while($row = mysql_fetch_array($result)) {
fputs($handle, join(';', $row)."\n");
}
fclose($handle);
$row is an array, you must join it (or access the elements )
$row is not a string, you have to make it a string before you can put it into a file.
And you have to change $scoredata to $scoredata[] because, it is now being overwritten continiously.
You can use print_r function with second parameter set true.
$str = print_r($row, true);
fwrite($handle,implode("\r\n", $str));
Or you can serialize the array
$str = serialize($row);
fwrite($handle,implode("\r\n", $str));

Categories