PHP SQL - Order By Date failing due to "," - php

I have a very strange issue. I am querying data and formatting it into a json. The format works great, but when i try to add a case that prevents a , from appearing in the last item of the json, the "Order By Date" of my SQL statement doesn't work, i just orders it by ID. Any thoughts why?
$sql = "SELECT * FROM events ORDER BY date";
$res = mysql_query($sql,$con);
$number = mysql_num_rows($res);
$json = 'var event_data={';
$i = 1;
while ($row = mysql_fetch_assoc($res))
{
$json .= '"'.$row['id'].'": {';
$json .= '"loc_id":"'.$row['loc_id'].'"';
$json .= ', "type":"'.$row['type'].'"';
$json .= ', "time":"'.$row['time'].'"';
$json .= ', "date":"'.$row['date'].'"}';
if ($i < $number)
{
$json .= ','; //<----- this is the problem child
}else{
$json .= '';
}
$i ++;
}
$json .= '};';
echo $json;

Please stop what you're doing now and check out: http://php.net/manual/en/function.json-encode.php
Building your own json encoder is going to be difficult to do correctly and will take quite take quite a bit of processing if you're doing it from PHP. Build up your data structure using PHP then encode the entire thing in one pass:
$o = array();
while ( $row = mysql_fetch_assoc($res) ) {
$n = array();
$n['loc_id'] = $row['loc_id'];
$n['type'] = $row['type'];
# ...
$o[ $row['id'] ] = $n;
}
echo json_encode($o);

Related

PHP with JSON issue

I'm new to PHP and I've encountered an issue that is driving me crazy. Perhaps someone here can let me know what I'm doing wrong.
I have a from that a user fills out. The below script is using the date entered into the mysql database to generate json data:
<?php
include("../includes.php");
$sq = new SQL();
$TableName = "permissions";
$Fields = $_POST["Fields"];
$FieldsSTR = "`" . str_replace("*;*","`,`", $Fields) . "`";
$Join = "AND";
$Start = 0;
$Limit = $_POST["Limit"];
if($Limit == "")$Limit = 1000;
$Where = $_POST["Where"];
$WhereSTR = "";
if($Where !== "")$WhereSTR = str_replace("*;*"," $Join ", $Where);
$q = "SELECT $FieldsSTR FROM `$TableName` $WhereSTR";
$data = $sq->sqlQuery($q);
if(sizeof($data)>0)array_shift($data);
header("Content-Type: application/json");
echo "[";
foreach($data as $k=>$line){
echo "[";
echo "\"" . str_replace("*;*","\",\"",$line) . "\"";
echo "]";
if($k < sizeof($data) - 1)echo ",";
}
echo "]";
exit;
?>
The problem that I'm having is that it has stopped working. One day it's fine and the next day it's not working. I'm thinking that maybe the cause of this problem is that crazy user data has been entered into the database. In my foreach statement I tried to replace the ";" with a "" tag, but that didn't work.
Has anyone encountered this issue before? Perhaps someone can point me in the right direction!
Thanks
Jason
Thanks everyone for your input. I was able to stumble on an fix to my immediate problem. I changed my foreach loop to the following:
foreach($data as $k=>$line){
$parts = explode("*;*",$line);
$NEWLINE = array();
for($i = 0;$i < sizeof($parts);$i++){
$value = $parts[$i];
$value = str_replace("\r","<br>",str_replace("\n","<br>",$value));
$NEWLINE[] = "\"" . $value . "\"";
}
$FINDATA[] = "[" . implode(",",$NEWLINE) . "]";
}
But I will now look into into using json_encode() as mentioned in the comments.
Thanks,
Jason

Removing last comma in the foreach query in php mysql

Im using a foreach loop to echo out some values from my database and seperating each of them by commas but last comma how we can remove
echo $string='"paymentmethods":';
echo $string='"Bank":[';
$sql2 = "SELECT * FROM paymentmethods where cid=587 ";
$query = $this->db->query($sql2);
foreach ($query->result() as $row){
echo '{';
echo $string = 'accname:'.$row->acc.',' ;
echo $string = 'country:'.$row->IBAN.',' ;
echo $string = 'Iban:'.$row->Bankname.',' ;
echo $string = 'Bankname:'.$row->Bankname.',' ;
echo $string = '},';
}
echo $string = '],';
"paymentmethods":"Bank":[{accname:0034430430012,country:AE690240002520511717801,Iban:ARABIC BANK NAME,Bankname:ARABIC BANK NAME,},{accname:0506796049,country:DE690240002520511717801,Iban:ARABIC BANK NAME,Bankname:ARABIC BANK NAME,},]
Here see the comma is repeating after the name ends. and also after the end of brackets
The comma is there because you have written it in your code. Change the lines to this :
// same as above
echo $string = 'Bankname:'.$row->Bankname. ;
echo $string = '}';
}
echo $string = ']';
a common way to do this is to do this way :
$sep = '';
$result = '';
foreach($myarray as $value) {
$result .= $sep.$value;
$sep = ',';
}
this way, you don't have a beginning or ending comma.
But as comments say, you are doing a "json_encode" by yourself... you should use json_encode / decode instead.

PHP Last in array to CSV

I have been trying to get this code to work for ages now and have looked at other questions but it is not working for me. Any guidance is greatly appreciated.
In context, there is a sql query to bring back all of the results for today's entries. These are converted to a CSV file every day. To import into the software then the end of each row must return "" and a carriage return except the last row which should not add a carriage return.
The code is below:
$xo1 = "\"\"";
$xo2 = "\r\n";
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
if(++$i === $columns_total){
$xo1 = "";
$xo2 = "";}
}
$output .= $xo1;
$output .= $xo2;
}
I guess rtrim() should do the job, if I got the question right.
while ( $row = mysql_fetch_array( $sql ) ) {
foreach( $row as $column ) {
$output .= sprintf( '"%s",""' . "\r\n" , $column );
}
}
rtrim( $output, '""' . "\r\n" );
You can also use the index of the loop for this problem. When index is above zero apply the $xo1 and $xo2. For example:
for ($i = 0; $i < $columns_total; $i++) {
if ( $i > 0 ) {
$output .= $xo1 . $xo2;
}
// now apply other workings
$output .='"'.$row["$i"].'",';
}

Write a dot instead of a comma when it's last element in PHP

I have a while loop use to write a list. i'd like every element separated with a comma, but write a dot after the last one, not a coma.
Here is my code
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
echo '<strong>'.$row['name'].'</strong>, ';
}
But I don't know how to do that. I tried using count() or end(), but none of these works. A little help would be great !
$html = array();
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
$html[] = '<strong>' . htmlspecialchars($row['name']) . '</strong>';
// --------------------^^^^^^^^^^^^^^^^! (1)
}
$html = implode(', ', $html) . '.';
(1) - Never output data to HTML without escaping it properly.
I like the use the implode function for this :)
$list = array();
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
$list[] = '<strong>'.$row['name'].'</strong>';
}
$string = implode(", " , $list);
echo $string . ".";
HTH
Try this:
$exec = mysql_query($req);
$output = array();
while ($row = mysql_fetch_assoc($exec)){
$output[] = '<strong>'.$row['name'].'</strong>';
}
echo implode(',', $output), '.';
Build the string but don't output. Then, trim off the command and add a fullstop:
$exec = mysql_query($req);
$output = "";
while ($row = mysql_fetch_assoc($exec))
{
$output .= '<strong>'.htmlentities($row['name']).'</strong>, ';
}
if($output) echo rtrim($output, ', ').".";

Create a comma-separated string from a single column of an array of objects

I'm using a foreach loop to echo out some values from my database, I need to strip the last comma from the last loop if that makes sense.
My loop is just simple, as below
foreach($results as $result){
echo $result->name.',';
}
Which echos out
result,result,result,result,
I just need to kill that pesky last comma.
Better:
$resultstr = array();
foreach ($results as $result) {
$resultstr[] = $result->name;
}
echo implode(",",$resultstr);
1. Concat to string but add | before
$s = '';
foreach ($results as $result) {
if ($s) $s .= '|';
$s .= $result->name;
}
echo $s;
2. Echo | only if not last item
$s = '';
$n = count($results);
foreach ($results as $i => $result) {
$s .= $result->name;
if (($i+1) != $n) $s .= '|';
}
echo $s;
3. Load to array and then implode
$s = array();
foreach ($results as $result) {
$s[] = $result->name;
}
echo implode('|', $s);
4. Concat to string then cut last | (or rtrim it)
$s = '';
foreach ($results as $result) {
$s .= $result->name . '|';
}
echo substr($s, 0, -1); # or # echo rtrim($s, '|');
5. Concat string using array_map()
echo implode('|', array_map(function($result) { return $result->name; }, $results));
$result_names = '';
foreach($results as $result){
$result_names .= $result->name.',';
}
echo rtrim($result_names, ',');
I've been having the same issue with this similar problem recently. I fixed it by using an increment variable $i, initializing it to 0, then having it increment inside the foreach loop. Within that loop place an if, else, with the echo statement including a comma if the $i counter is less than the sizeof() operator of your array/variable.
I don't know if this would fix your issue per se, but it helped me with mine. I realize this question is years-old, but hopefully this will help someone else. I'm fairly new to PHP so I didn't quite understand a lot of the Answers that were given before me, though they were quite insightful, particularly the implode one.
$i=0;
foreach ($results as $result) {
$i++;
if(sizeof($results) > $i) {
echo $result . ", ";
} else {
echo $result;
}
}
In modern PHP, array_column() will allow you to isolate a column of data within an array of objects.
Code: (Demo)
$results = [
(object)['name' => 'A'],
(object)['name' => 'B'],
(object)['name' => 'C']
];
echo implode(',', array_column($results, 'name'));
Output:
A,B,C
That said, since you are iterating a result set, then you may be better served by calling a CONCAT() function in your sql, so that the values are already joined in the single value result set.
If you are processing a collection in Laravel, you can pluck() and implode():
$collection->pluck('name')->implode(',')
$arraySize = count($results);
for($i=0; $i<$arraySize; $i++)
{
$comma = ($i<$arraySize) ? ", " : "";
echo $results[$i]->name.$comma;
}
Not as pretty, but also works:
$first=true;
foreach($results as $result){
if(!$first) { echo ', '; }
$first=false;
echo $result->name;
}
Another smart way is:
foreach($results as $result){
echo ($passed ? ',' : '') . $result->name;
$passed = true;
}
In this case at first loop $passed is NULL and , doesn't print.
I know this is an old thread, but this came up recently and I thought I'd share my alternate, cleaner way of dealing with it, using next().
$array = array("A thing", "A whatsit", "eighty flange oscillators");
foreach( $array as $value ){
echo $value;
$nxt = next($array);
if($nxt) echo ", "; // commas between each item in the list
else echo ". And that's it."; // no comma after the last item.
}
// outputs:
// A thing, A whatsit, eighty flange oscillators. And that's it.
play with it here
I have to do this alot because I'm always trying to feed numbers in to jplot, I find its easier to put the comma in the front of the loop like so:
foreach($arrayitem as $k){ $string = $string.",".$k;
}
and then chop off the first character (the comma) using substr, it helps if you know a guestimate of long your string will be, I'm not sure what the limit on substr max character is.
echo substr($a,1,10000000);
hope this helps.
$a[0] = 'John Doe';
$a[1] = 'Jason statham';
$a[2] = 'Thomas Anderson';
$size = count($a);
foreach($a as $key=>$name){
$result .= $name;
if($size > $key+1) $result .=', ';
}
echo $result;
<?php
$return = array(any array)
$len = count($return);
$str = '';
$i = 1;
foreach($return as $key=>$value)
{
$str .= '<a href='.$value['cat_url'].'>'.$value['cat_title'].'</a>';
if($len > $i)
{
$str .= ',';
$i = $i+1;
}
}
echo $str;
?>
<?php
$i = 1;
$count = count( $results );
foreach( $results as $result ) {
echo $result->name;
if ( $i < $count ) echo ", ";
++$i;
}
?>
This is what I normally do, add a comma before the item rather than after, while ignoring the first loop.
$i = 0;
$string = '';
foreach($array as $item){
$string .= ($i++ ? ',' : '').$item;
}
First get all the output by using output buffering. Then, trim the comma and display it. So, do it like this:
ob_start();
foreach($results as $result)
{
echo $result->name.',';
}
$output = ob_get_clean();
echo rtrim($output, ',');
The output buffering method helps if the inside loop is very big (and OP is posting here just for brevity), then using OB is easier without changing the internals of the loop.

Categories