Convert SQL query to csv using odbc - php

I'm trying to get data from an off-site Miscrosoft SQL database using php's odbc connection, convert certain queries against it to arrays, and then turn those arrays into a csv that my cms can read and import. I'm able to succesfully conncect and return some results from the database, but my lack of php and SQL skills is killing me.
What I have right now, which is not much, but does what it's supposed to do:
$result = odbc_tables($connect);
$tables = array();
while (odbc_fetch_row($result))
{
if(odbc_result($result,"TABLE_TYPE")=="TABLE")
echo"<br>".odbc_result($result,"TABLE_NAME");
}
Is there any clear resource on the web on how to do what I want to do? The official php documentation seems to be about the most unhelpful documentation ever. A basic example: I want to return the entries here into csv format. I can get them in array format:
$query = "SELECT TOP 10 * FROM Communities";
$result = odbc_exec($connect, $query);
if ( $result )
{
while ( ($row = odbc_fetch_array($result)) )
{
print_r($row);
}
odbc_free_result($result);
}
else
{
echo 'Exec error: ' . odbc_errormsg();
}
odbc_close($conn);
Wish I had more, but I'm a bit lost on where to go next.

Using the tips, here's the working solution:
$theArray = array();
while ( ($row = odbc_fetch_array($result)) )
{
array_push($theArray, $row);
}
$header = array('Name', 'Hours', 'Fees', 'Notes', 'ShortDescription', 'URL');
$fp = fopen('array.csv', 'w');
fputcsv($fp, $header);
foreach ($theArray as $lines)
{
fputcsv($fp, $lines);
}

I just got done doing the exact project that you are asking about. I am running php 5.2 so you may be able to deal with the csv file more easily in a newer version. Here is my code:
<?php
// Uncomment this line for troubleshooting / if nothing displays
ini_set('display_errors', 'On');
$myServer = "GSRBI";
$myUser = "webuser";
$myPass = "Webuser1";
$myDB = "GSRBI";
$dbhandle = odbc_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$return = odbc_exec($dbhandle, 'select * from GSRBI.dbo.BounceBackEmail');
$subscribers_array = array();
$db_row = '';
$arrayrow = 0;
while ( $db_row = odbc_fetch_array($return) )
{
$arrayrow++;
$array[] = array(
'card_num' => $db_row['PlayerAccountNumber']
,'last_name' => ucfirst(strtolower($db_row['LastName']))
,'first_name' => ucfirst(strtolower($db_row['FirstName']))
,'email' => $db_row['EMailAddress']
,'earned_on_date' => date('m/d/Y', strtotime('-1 days'))
,'free_play' => $db_row['Offer1']
,'valid_through_date' => date('m/d/Y', strtotime('+15 days'))
);
}
echo print_r($arrayrow, true); ## display number of rows for sql array
echo " rows in ODBC ";
// Creates an array with GSR webteams contact info
$array1[] = array(
'card_num' => "123456789"
,'last_name' => "GSRwebteam"
,'first_name' => "GSRwebteam"
,'email' => "webteam#something.com"
,'earned_on_date' => date('m/d/Y', strtotime('-1 days'))
,'free_play' => "9"
,'valid_through_date' => date('m/d/Y', strtotime('+15 days'))
);
$result = array_merge((array)$array, (array)$array1); ## merge the two arrays together
// This will convert the array to csv format then save it
## Grab the first element to build the header
$arr = array_pop( $result );
$temp = array();
foreach( $arr as $key => $data )
{
$temp[] = $key;
}
$csv = implode( ',', $temp ) . "\n";
$csv .= to_csv_line( $arr ); ## Add the data from the first element
foreach( $result as $arr ) ## Add the data for the rest
{
$csv .= to_csv_line( $arr );
}
//echo print_r($csv, true); ## Uncomment to test output1
$f = fopen('reports/bounceback-'.date('m-d-Y').'.csv', "w");
fwrite($f, $csv);
fclose($f);
Echo "The report has ran";
return $csv;
function to_csv_line( $result )
{
$temp = array();
foreach( $result as $elt )
{
$temp[] = '' . addslashes( $elt ) . '';
}
$string = implode( ',', $temp ) . "\n";
return $string;
}

Related

CSV overwrite line if same date else append to new line

I want to write $totalToday data from API to csv file. If current date not existed, append new record for current date. I've came with following solution.
$search = date("d/m/Y");
$lines = file('data.csv');
$line_number = false;
foreach($lines as $key => $line) {
$line_number = (strpos($line, $search) !== FALSE);
}
if(!$line_number){
$entry = array(date("d/m/Y"), $totalToday);
$fp = fopen('data.csv', 'a');
fputcsv($fp, $entry);
fclose($fp);
}
My problem is $totalToday from API get updated time to time. I want to record the latest update. so I replaced $search = date("d/m/Y"); with $search = date("d/m/Y"), $totalToday now I have multiple record for same date in my data.csv. I want to overwrite the current date record with very latest data without append to new line. How to accomplish my requirement
Example data: (first rows)
date,newCases,totalToday
13/04/2020,21,110
14/04/2020,26,125
14/04/2020,30,130
I want to replace 14/04/2020,26,125 with 14/04/2020,30,130
One approach could be this:
<?php
$search = '14/04/2020';
$other_data_from_api = array(188,102);
$lines = file('data.csv');
//Create a new array and set all dates as keys
//The latest set key would be the current
$new_arr = array();
foreach($lines as $line) {
$exp = explode(',', $line);
$new_arr[$exp[0]] = array($exp[1], $exp[2]);
}
/*
So in your example:
13/04/2020,21,110
14/04/2020,26,125
14/04/2020,30,130
the array $new_arr would contain:
[13/04/2020] => Array
(
[0] => 21
[1] => 110
)
[14/04/2020] => Array
(
[0] => 30
[1] => 130
)
*/
//Rewrite the whole file with values from this new array
$fp = fopen('data.csv', 'w');
foreach($new_arr as $key=>$line) {
$entry = $key . ',' . implode(',', $line);
fputs($fp, $entry);
}
fclose($fp);
You could also:
//Rewrite the whole file with values from this new array
//And include the actual data from the API
//(Then 188,102 would be included with the data of the $search variable)
$fp = fopen('data.csv', 'w');
foreach($new_arr as $key=>$line) {
if ($search == $key) {
$entry = $search . ',' . implode(',', $other_data_from_api);
}
else {
$entry = $key . ',' . implode(',', $line);
}
fputs($fp, $entry);
}
fclose($fp);

PHP script to rearrange csv data and output as csv

I have the following data in a csv file.
I need to rearrange the data and concate it into 2 columns. the columns will be SKU and Feature. Where SKU = SKU and Feature will be derivative from other columns in the following format.
For yellow marked row: Feature column data will be: Edge:Square Edge;Wide Plank|Finish:Glossy;Smooth|Grade:A(Select & Better/Prestige)|Installation Location:Second Floor;Main Floor........
I could parse the csv and stucked.
$lines = explode( "\n", file_get_contents( '3b.csv' ) );
$headers = str_getcsv( array_shift( $lines ) );
$data = array();
foreach ( $lines as $line ) {
$row = array();
foreach ( str_getcsv( $line ) as $key => $field )
if($headers[$key]=='sku'){
$row[ $headers[ $key ] ] = str_replace(",",";",$field);
}
if($headers[$key]!='sku' && $field!='') {
$row['feature'] = $headers[ $key ].":".str_replace(",",";",$field)."|";
}
$row = array_filter( $row );
$data[] = $row;
}
echo "<pre>";
print_r($data);
echo "</pre>";
Anyone please help me to do this or suggest any script to do this.
You haven't provided the actual text of your incoming csv files, so I will assume that parsing it normally will work properly.
I have borrow my script from your next two questions to unconditionally process your data.
The header row's data is used as a lookup array for the feature names.
Code: (untested)
$file = fopen("3b.csv", "r");
$headers = fgetcsv($file);
$final_array = [];
while (($row = fgetcsv($file)) !== false) {
$sku = $row[0];
unset($row[0]);
foreach ($row as $featureNameIndex => $featureValues) {
foreach (explode(',', $featureValues) as $featureValue) {
$final_array[] = [
'sku' => $sku,
'feature' => "{$headers[$featureNameIndex]}:{$featureValue}"
];
}
}
}
fclose($file);
var_export($final_array);
This approach will generate an indexed array of associative arrays -- each containing two-elements.
Features with multiple values are divided and stored as separate subarrays.

Export to CSV changes in PHP

I am working on Export to CSV in PHP. I have code that works fine it gives me output in ExcelSheet as I want.
Code snippet:
public function generate_csv() {
$data_rows = array();
$table = 'ProductDetails';
$data_rows = array();
global $wpdb, $bp;
$data= $wpdb->get_results("SELECT * FROM " . $table . "");
$fh = #fopen( 'php://output', 'w' );
foreach ($data as $u ) {
$row = array();
$row[0] = $u->productCode;
$row[1] = $u->productTitle;
$row[2] = $u->productDescription;
$row[3] = $u->specification;
$row[4] = $u->whereToBuy;
$data_rows[] = $row;
}
header("Pragma: public");
... Some more header ...
header("Content-Transfer-Encoding: binary");
fputcsv( $fh, $header_row );
foreach ( $data_rows as $data_row ) {
fputcsv( $fh, $data_row );
}
fclose( $fh );
die();
}
As you can see in code I am hard coding all column names and creating array. The problem is if phpMyAdmin add/remove column in database then to get perfect ExcelSheet necessary changes need to make in this code also. Can any one please help me to make this code dynamic.? Like what should be instead of $row[0], $row[1], $row[2].... ??
Thank You
More global approach is to use double foreaches
$data_rows=array();
foreach ($data as $u ) {
$row = array();
foreach ($u as $field)
{
$row[] = $field; // collect dynamic row fields
}
$data_rows[] = $row; // each row will have own array of fields
}
/// EDITED
public function generate_csv($table) // better to have table name here
{
$data_rows = array();
$data_rows = array();
global $wpdb, $bp;
$sql = "SELECT * FROM " . $table . "";
$data= $wpdb->get_results($sql);
$fh = #fopen( 'php://output', 'w' );
//following the example from: https://stackoverflow.com/a/31068464/1171074
$header_data=array();
foreach ( $wpdb->get_col( "DESC " . $table, 0 ) as $column_name ) {
$header_data[] = $column_name;
}
array_push($data_rows,$header_data); // first array will be columns names
foreach ($data as $u ) {
$row = array();
foreach ($u as $field)
{
$row[] = $field; // collect dynamic row fields
}
$data_rows[] = $row; // each row will have own array of fields
}
............ // rest of the code
}
You can use the virtual INFORMATION_SCHEMA.COLUMNS table to get the column names, like so:
"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = {$table}"
This should get you pretty close, if not all the way there. It will query the table, build a headers row for the csv, then it will assemble each data row. You shouldn't need to know the row name, if you iterate the response row as value..
I apologize up front if it's a little buggy, since I don't have a PHP box handy where I'm at to verify the precise syntax.
public function generate_csv() {
global $wpdb;
global $bp;
$headers = array();
$data_rows = array();
$table = 'ProductDetails';
$data_rows = array();
$header_row;
# determine table field names
$table_sql = sprintf("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s'",$table);
# this will run the query and stuff field names into
$resp = $wpdb->get_results($table_sql);
foreach($resp as $row){
array_push($headers,$row[0]);
}
# get the records from the datbase
$data= $wpdb->get_results(sprintf("SELECT * FROM %s",$table));
# open output handle
$fh = #fopen( 'php://output', 'w' );
foreach ($data as $record ) {
$row = array();
foreach($record as $value){
array_push($row,$value);
}
array_push($data_rows,$row);
}
header("Pragma: public");
... Some more header ...
header("Content-Transfer-Encoding: binary");
fputcsv( $fh, $headers );
foreach ( $data_rows as $data_row ) {
fputcsv( $fh, $data_row );
}
fclose( $fh );
return;
}

Php json_encode from mysql > output without column names

this is my code on a php page connected to mysql server.
$temp = array();
while($row = mysqli_fetch_assoc($result)) {
$temp[] = $row;
}
echo json_encode($temp);
The output is:
[{"column1":"1448741941","column2":"951"},{"column1":"1448747281","column2":"862"}]
That's is including the column title + data, and i wanna know how can i get only datas, like
[[1448741941,951],[1448747281,862]]
Thanks for the help!
Here is the quick answer, send in an array with the data only:
$temp = array();
while($row = mysqli_fetch_assoc($result)) {
$temp[] = array( $row['column1'], $row['column2'] );
}
echo json_encode($temp);
Edit You might actually whant this too JSON_NUMERIC_CHECK:
$temp = array();
while($row = mysqli_fetch_assoc($result)) {
$temp[] = array( $row['column1'], $row['column2'] );
}
echo json_encode($temp, JSON_NUMERIC_CHECK);
Another way is this:
$temp[] = array(
intval( $row['column1'] ),
intval( $row['column2'] ) );

Upload,retrive and display image in HBase using Thrift and Php

I have set up HBase and trying to use Thrift-Php to upload an image and then display it. I have one table with one column family named info and used something like:
$tmpName=$_FILES["file"]["tmp_name"];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
try {
$mutations = array(
new Mutation( array(
'column' => 'info:pic',
'value' => $data
) ),
);
$client->mutateRow( $t, $username, $mutations );
} catch ( IOError $e ) {
echo( "expected error: {$e->message}\n" );
}
Which seems to work as it stores something in Hbase and then
$arr = $client->getRow($t, $username);
foreach ( $arr as $k=>$TRowResult ) {
$values = $TRowResult->columns;
asort( $values );
foreach ( $values as $k=>$v ) {
$usr= $v->value;
$content=$_GET['username'];
header('Content-type: image/jpg');
echo $usr;
}
}
But I get an error message saying that the image contains errors. Can someone provide an example in Php?
Thank you.
I think, your problem is that you use $data = addslashes($data); when you store data. There's no need to quote characters when storing them to HBase.
And, you can retrieve data like this:
$values = $TRowResult->columns;
$usr= $values['info:pic']->value;
$content=$_GET['username'];
header('Content-type: image/jpg');
echo $usr;

Categories