encode php recordset in custom format - php

I'm currently have a recordset created with dreamweaver and have encode the results in json format which work fine.
Recordset
$maxRows_rs_feeds = 3;
$pageNum_rs_feeds = 0;
if (isset($_GET['pageNum_rs_feeds'])) {
$pageNum_rs_feeds = $_GET['pageNum_rs_feeds'];
}
$startRow_rs_feeds = $pageNum_rs_feeds * $maxRows_rs_feeds;
mysql_select_db($database_vivalooks, $vivalooks);
$query_rs_feeds = "SELECT fname,lname FROM profile";
$query_limit_rs_feeds = sprintf("%s LIMIT %d, %d", $query_rs_feeds, $startRow_rs_feeds, $maxRows_rs_feeds);
$rs_feeds = mysql_query($query_limit_rs_feeds, $vivalooks) or die(mysql_error());
$row_rs_feeds= mysql_fetch_assoc($rs_feeds);
if (isset($_GET['totalRows_rs_feeds'])) {
$totalRows_rs_feeds = $_GET['totalRows_rs_feeds'];
} else {
$all_rs_feeds = mysql_query($query_rs_feeds);
$totalRows_rs_feeds = mysql_num_rows($all_rs_feeds);
}
$totalPages_rs_feeds = ceil($totalRows_rs_feeds/$maxRows_rs_feeds)-1;
do {
echo json_encode($row_rs_feeds);
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
mysql_free_result($rs_feeds);
Recordset Results
{"fname":"Benjamin","lname":"Blay"}{"fname":"Alfread","lname":"Mark"}{"fname":"yaa","lname":"tiwaa"}
But i want the results to be encode like this rather
[{"fname":"Benjamin","lname":"Blay"},{"fname":"Alfred","lname":"Mark"},{"fname":"yaa","lname":"tiwaa"}]

Try
do {
$json[]=json_encode($row_rs_feeds);
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
echo "[".implode(", ", $json)."]";
OR
do {
$rows[] = $row_rs_feeds;
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
echo json_encode($rows);

You can change your loop to look like this:
echo "[";
$count = 0;
do {
if($count !== 0)
echo ",";
$count++;
echo json_encode($row_rs_feeds);
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
echo "]";
$count is there just to skip first "," so you don't get [,{...},{...}] or you can put it like false/true... I just can't remember right now what is better in case you have 10k steps loop...

Try:
do {
$rows[] = $row_rs_feeds;
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
echo json_encode($rows);

Related

Adwords Exported CSV Report Parsing in PHP not working

I have created a table which I am trying to populate with data from a CSV file exported from AdWords. Following is my table -
The table is only displayed when ajax call is successful because the table HTML is returned by the page I make ajax request to. As you can see I'm getting the table columns and the table is being populated properly but I'm not getting the values for some reason.
GENERATING TABLE WITH VALUES FROM FUNCTION
$campaigns_data = getCampaignsCSVData($account_name);
$campaigns_columns = $campaigns_data['columns'];
$campaigns_values = $campaigns_data['values'];
if(!empty($campaigns_columns) && !empty($campaigns_values)){
echo '<h4>Campaign Totals</h4>'.PHP_EOL;
getCampaignsTable($campaigns_columns,$campaigns_values,$campaigns_included_cols,'Clicks','DESC');
}
FUNCTION TO GENERATE CAMPAIGNS TABLE
function getCampaignsTable($columns,$values,$included_cols,$sort_by='',$sort_dir='ASC'){
$values_by_column_key = array();
foreach($values as $key=>$row){
$processed_cols = array();
foreach($row as $key=>$col){
if(is_numeric(str_replace(',','',$col))){
$col = str_replace(',','',$col);
}
if($col[0] == '$'){
$processed_cols[$columns[$key]] = str_replace('$','',$col);
}else{
$processed_cols[$columns[$key]] = $col;
}
}
$values_by_column_key[] = $processed_cols;
}
if(!empty($sort_by)){
usort($values_by_column_key, function($a,$b)use($sort_by,$sort_dir){
if($sort_dir == 'ASC'){
return $a[$sort_by] > $b[$sort_by];
}elseif($sort_dir == 'DESC'){
return $a[$sort_by] < $b[$sort_by];
}
});
}
echo '<table class="data-table">'.PHP_EOL;
echo '<thead>'.PHP_EOL;
echo '<tr>'.PHP_EOL;
if(!empty($included_cols)){
foreach($included_cols as $col){
echo '<th>'.$col['label'].'</th>'.PHP_EOL;
}
}
echo '</tr>'.PHP_EOL;
echo '</thead>'.PHP_EOL;
echo '<tbody>'.PHP_EOL;
$row_count = 0;
foreach($values_by_column_key as $key1=>$row){
$row_count++;
if($row_count <= RESULT_LIMIT){
echo '<tr>'.PHP_EOL;
foreach($included_cols as $key2=>$inc_cols){
if($inc_cols['format'] == 'currency'){
echo '<td>'.$inc_cols['currency_symbol'].$row[$key2].'</td>'.PHP_EOL;
}else{
echo '<td>'.$row[$key2].'</td>'.PHP_EOL;
}
}
echo '</tr>'.PHP_EOL;
}
}
echo '</tbody>'.PHP_EOL;
echo '</table>'.PHP_EOL;
}
FUNCTION TO READ AND PARSE CSV FILE
function getCampaignsCSVData($account){
$data = array();
$dir = ADWORDS_REPORTS_DIR.$account.'/';
$filename = ADWORDS_CAMPAIGN_FILE;
$filepath = $dir.$filename;
$row_count = 0;
if(file_exists($filepath)){
$csvfile = #fopen($filepath,'r');
if($csvfile){
while(!feof($csvfile)){
$row = fgets($csvfile);
$row = preg_replace("/[^a-zA-Z ]/", "", $row);
$row_count++;
$row_data = '';
if(stristr($row,CAMPAIGNS_REPORT_IN_COLUMNS_WORD)){
$row_data = str_replace('Impr.','Impressions',$row);
$row_data = str_replace('Interactions','Clicks',$row_data);
$data['columns'] = str_getcsv($row_data);
$columns_row_index = $row_count;
} elseif($row_count > $columns_row_index && !empty($columns_row_index)){
$row_data = $row;
if(!stristr($row,'Total') && !empty($row)){
$data['values'][] = str_getcsv($row_data);
}
}
}
}
fclose($csvfile);
}else{
$data = false;
}
return $data;
}
This code has been working for a long time but it suddenly stopped working recently without changing anything. I can't seem to get my head around it because I can't find any error. Please help. Thanks!

Echo array values of column not working

I want to display the values of my array. but instead of displaying:
1509 1510 1511 it display ArrayArrayArray. What does it mean?
include("db_PSIS.php");
$sql_dc = "SELECT Child, Datecode
FROM traveller_merging15
WHERE Parent='" . $_REQUEST["txt_traveller_no"] . "'
ORDER BY Merge_ID ASC";
$res_dc = mysql_query($sql_dc);
$dcode1 = $row_dc['Datecode'];
$storeArray = array();
if (!$res_dc) {
echo "No data fetched!";
} else {
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
$storeArray[] = $dcode1;
echo "{$storeArray} <br>";
}
//$str_dc=implode(",",$storeArray);
//echo $str_dc;
}
You are assign the value of $row_dc['Datecode']; before fetch data from database. You need to do fetch data inside while loop and echo it
$res_dc = mysql_query($sql_dc);
if (!$res_dc) {
echo "No data fetched!";
} else {
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
echo $row_dc['Datecode'];
}
}
Note:- mysql is deprecated instead use mysqli or PDO
else {
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
$storeArray[] = $dcode1;
echo "{$storeArray} <br>";
}
instead try
else {
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
$storeArray[] = $dcode1;
echo "{$storeArray[0]} <br>";
}
Try this,
else {
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
$child = $row_dc['Child'];
$Datecode = $row_dc['Datecode'];
echo "$child <br> $Datecode";
}
if you are getting more that 1 row, use for() loop
else {
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
$count = count($row_dc);
for($i = 0; $i < $count; $i ++){
$child = $row_dc[$i]['Child'];
$Datecode = $row_dc[$i]['Datecode'];
echo "$child <br> $Datecode";
}
}
-first array don't print value using echo
-use print_r($array) to print key value pair(print a array)
your solution is
$i = 0;
while ($row_dc = mysql_fetch_array($res_dc, MYSQL_ASSOC)) {
$storeArray[$i] = $dcode1;
echo $storeArray[$i].'<br>';
$i++;
}
NOTE::-- Use single Quote instead of double Quote and mysql is deprecated instead use mysqli or PDO

php (or c++) how to read data of multiple formats from binary file

i have a question that i cant find the answer
i use the following code to write data from database to binary file:
$data = array();
$prev = 1;
$i=0;
$query="select wc.MAC, ws.SIGNAL_STRENGTH, ws.ID, ws.USER_SCAN from wifi_cell as wc, wifi_scan as ws where ws.WIFI_CELL=wc.ID";
$result=kmysql_query($query);
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC)) {
$data[] = array(0,0,0,null,$row['MAC'],$row['SIGNAL_STRENGTH'],null,$row['USER_SCAN']);
$i++;
}
mysql_free_result($result);
$j=0;
$query="select ul.LATITUDE, ul.LONGITUDE,ul.ALTITUDE, ul.TIME from user_location as ul where 1";
$result=kmysql_query($query);
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC)) {
while ($j<$i) {
if ($data[$j][7] == $prev) {
$data[$j][0] = $row['LATITUDE'];
$data[$j][1] = $row['LONGITUDE'];
$data[$j][2] = $row['ALTITUDE'];
$data[$j][3] = $row['TIME'];
$j++;
}
else {
$prev = $data[$j][7];
break;
}
}
}
mysql_free_result($result);
$handle = fopen('C:\\Users\\Duc Nguyen\\Desktop\\text1.bin', 'r+');
ftruncate($handle, 0);
fclose($handle);
for ($j=0;$j<$i;$j++) {
$data[$j][0] = pack("d*",$data[$j][0]);
$data[$j][1] = pack("d*",$data[$j][1]);
$data[$j][2] = pack("d*",$data[$j][2]);
$data[$j][3] = pack("A*",$data[$j][3]);
$data[$j][4] = pack("Z*",$data[$j][4]);
$data[$j][5] = pack("d*",$data[$j][5]);
$data[$j][6] = pack("A*",$data[$j][6]);
$data[$j][7] = pack("d*",$data[$j][7]);
file_put_contents('C:\\Users\\Duc Nguyen\\Desktop\\text1.bin', $data[$j], FILE_APPEND);
}
but now the binary file contains many types of data and i dont know how to read it. can you please show me how to read them in php? and also c++?

problem in the output of query - php+json

function tableOne() {
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$i = 0;
while($row = mysql_fetch_assoc($query)) {
$arr[] = array($row[valor]);
++$i;
}
echo json_encode($arr);
}
}
the output will be
[["15573"],["31978"],["11227"],["5752"],["20817"],["32182"]]
i need something like:
["15573","31978","11227","5752","20817","32182","10935"]
i tried some changes in the code but the output is not what i want.
thanks
You are placing sub-arrays in each element of your array. You should replace
$arr[] = array($row[valor]);
with
$arr[] = $row[valor];
The [] in $arr[] already adds each entry as an element of the array.
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$arr = array();
while ($row = mysql_fetch_assoc($query)) {
$arr[] = $row['valor']; // get rid of the array() wrapper
}
echo json_encode($arr);

How to add a <br/> after each result, but not last result?

This is my partial code:
while($row = $db->fetch_array($query))
{
echo $row['row_name'];
}
How can I make it so it will add a break tag after each result, but not the last result?
Put the output into an array, then join the array with implode:
$rows = array();
while($row = $db->fetch_array($query))
{
$rows[] = $row['row_name'];
}
echo implode('<br/>', $rows);
You could do this. No arrays or counters.
if($row = $db->fetch_array($query))
{
do {
echo $row['row_name']
} while($row = $db->fetch_array($query) && print("<br />"));
}
for ($idx = 0; $row = $db->fetch_array($query); $idx++)
{
if ($idx > 0) { echo "<br/>"; }
echo $row['row_name'];
}

Categories