Jump to content

How to *NOT* add a comma on the last echoed result


DaveLinger

Recommended Posts

<?php  

if (!$link = mysql_connect(localhost, x, x)) {
   echo 'Could not connect to mysql';
   exit;
}

if (!mysql_select_db(x, $link)) {
   echo 'Could not select database';
   exit;
}

$query="SELECT * FROM registry ORDER BY id ASC";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {

$id = $row["id"];
$owner = $row["owner"];
$year = $row["year"];
$texusername = $row["texusername"];
$texid = $row["texid"];
$location = $row["location"];
$lat = $row["lat"];
$lon = $row["lon"];

if($lat != ""){

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'},";

}

}

?>

 

Basically this retrieves all rows in the DB, and echoes the block if the latitude (lat) is set. I put a comma at the end of the echo so that it will correctly separate entries - problem is, the extra comma on the last echoed entry causes it to not work on IE. How can I make it echo the comma for every result except the final?

Link to comment
Share on other sites

I tried making it:

 

if($row > 0){echo ",";}

if($lat != ""){

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'}";

}

 

That way it adds the comma before every entry but the first (same result)

 

only problem with that code is that not all rows are echoed, only the ones with LAT set, so it doesn't work.

Link to comment
Share on other sites

$query1="SELECT COUNT(*) FROM registry ORDER BY id ASC";
$count = mysql_query($query1);

$query="SELECT * FROM registry ORDER BY id ASC";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {

$id = $row["id"];
$owner = $row["owner"];
$year = $row["year"];
$texusername = $row["texusername"];
$texid = $row["texid"];
$location = $row["location"];
$lat = $row["lat"];
$lon = $row["lon"];

if ($row < $count) {

if($lat != ""){

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'},";

}

}

elseif ($row == $count){

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'}";
}

 

Not sure, but that might work.  This way you are counting, and if the row is equal to the count, then you will echo the statement without the ,  There probably is a different way, but can give it a try.

Link to comment
Share on other sites

$query1="SELECT COUNT(*) FROM registry ORDER BY id ASC";
$count = mysql_query($query1);

$query="SELECT * FROM registry ORDER BY id ASC";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {

$id = $row["id"];
$owner = $row["owner"];
$year = $row["year"];
$texusername = $row["texusername"];
$texid = $row["texid"];
$location = $row["location"];
$lat = $row["lat"];
$lon = $row["lon"];

if ($row < $count) {

if($lat != ""){

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'},";

}

}

elseif ($row == $count){

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'}";
}

 

Not sure, but that might work.  This way you are counting, and if the row is equal to the count, then you will echo the statement without the ,  There probably is a different way, but can give it a try.

 

I see your logic, but it does not work. As I said, the query gets all rows in the DB, but only the rows with "lat" set are echoed, so the number of rows is not equal to the number of rows to be echoed.

Link to comment
Share on other sites

I believe this will run a query to select from the table where lat != ''

 

$query1="SELECT COUNT(*) FROM registry WHERE lat <> '' ORDER BY id ASC";
$count = mysql_query($query1);

$query="SELECT * FROM registry WHERE lat <> '' ORDER BY id ASC";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {

$id = $row["id"];
$owner = $row["owner"];
$year = $row["year"];
$texusername = $row["texusername"];
$texid = $row["texid"];
$location = $row["location"];
$lat = $row["lat"];
$lon = $row["lon"];

if ($row < $count) {

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'},";

}

elseif ($row == $count){

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'}";
}

Link to comment
Share on other sites

Count rows, run the loop x times - 1 and then add a final normal query without a comma, outside the loop

 

Again, that won't work because it retrieves all of the rows (34 rows total), but I only want to echo the rows which have LAT set, which, in this case, is 3.

I believe this will run a query to select from the table where lat != ''

 

$query1="SELECT COUNT(*) FROM registry WHERE lat <> '' ORDER BY id ASC";
$count = mysql_query($query1);

$query="SELECT * FROM registry WHERE lat <> '' ORDER BY id ASC";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {

$id = $row["id"];
$owner = $row["owner"];
$year = $row["year"];
$texusername = $row["texusername"];
$texid = $row["texid"];
$location = $row["location"];
$lat = $row["lat"];
$lon = $row["lon"];

if ($row < $count) {

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'},";

}

elseif ($row == $count){

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'}";
}

 

echoes nothing =/

Link to comment
Share on other sites

change the query lines to this and see if there is an error in the query.

 

$count = mysql_query($query1) or die ("Error in query: $query1. ".mysql_error());

$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error())

 

Updated, no errors.

Link to comment
Share on other sites

can you post the code you have again, there might be a } missing in it.  Please post from start to finish like the first post.  this is what I have right now.

 

$query1="SELECT COUNT(*) FROM registry WHERE lat <> '' ORDER BY id ASC";
$count = mysql_query($query1);

$query="SELECT * FROM registry WHERE lat <> '' ORDER BY id ASC";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {

$id = $row["id"];
$owner = $row["owner"];
$year = $row["year"];
$texusername = $row["texusername"];
$texid = $row["texid"];
$location = $row["location"];
$lat = $row["lat"];
$lon = $row["lon"];

if ($row < $count) {

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'},";

}

elseif ($row == $count){

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'}";
}

 

This is what I should have

 

$query1="SELECT COUNT(*) FROM registry WHERE lat <> '' ORDER BY id ASC";
$count = mysql_query($query1);

$query="SELECT * FROM registry WHERE lat <> '' ORDER BY id ASC";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {

$id = $row["id"];
$owner = $row["owner"];
$year = $row["year"];
$texusername = $row["texusername"];
$texid = $row["texid"];
$location = $row["location"];
$lat = $row["lat"];
$lon = $row["lon"];

if ($row < $count) {

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'},";

}

elseif ($row == $count){

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'}";
}
}

Link to comment
Share on other sites

psuedo (dumb) code:

 

<?php 

$q = mysql_query("select ...");

$results = array();

while ($result = mysql_fetch_array($q)) {
      if ($lat) $results[] = $result; // if it's something you plan on echoing, add it to the results array.. why you're not doing a where clause is beyond me, whatever.
}

for ($x=0; $x<count($results); $x++) {
     if ($x == count($results)) {
         echo $results[$x];
     } else {
         echo $results[$x] . ",";
     }
} 
?>

 

Ugliest code I have written in years.

Link to comment
Share on other sites

Shouldn't this work?

 

$query="SELECT * FROM registry WHERE lat <> '' ORDER BY id ASC";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
$count = mysql_num_rows($result);

while ($row = mysql_fetch_array($result)) {

$id = $row["id"];
$owner = $row["owner"];
$year = $row["year"];
$texusername = $row["texusername"];
$texid = $row["texid"];
$location = $row["location"];
$lat = $row["lat"];
$lon = $row["lon"];

if ($row < $count-1) {

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'},";

}

if ($row == $count-1){

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'}";
}

}

 

if I echo $count, I get 3, which is right - because the first row is #0, I subtract one from the count to match it up.

 

However it still echoes nothing.

 

Here's my complete code:

 

<?php  

if (!$link = mysql_connect(x, x, x)) {
   echo 'Could not connect to mysql';
   exit;
}

if (!mysql_select_db(x, $link)) {
   echo 'Could not select database';
   exit;
}

$query="SELECT * FROM registry WHERE lat <> '' ORDER BY id ASC";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
$count = mysql_num_rows($result);

while ($row = mysql_fetch_array($result)) {

$id = $row["id"];
$owner = $row["owner"];
$year = $row["year"];
$texusername = $row["texusername"];
$texid = $row["texid"];
$location = $row["location"];
$lat = $row["lat"];
$lon = $row["lon"];

if ($row < $count-1) {

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'},";

}

if ($row == $count-1){

echo "{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'}";
}

}

?>

Link to comment
Share on other sites

C'mon guys this isn't that difficult.

 

Method 1

Append each item to an array and call implode on the array.

$array = Array();
for($i = 1; $i <= 10; $i++){
  $array[] = $i;
}
echo implode(', ', $array);

 

Method 2

Append to a string var and use rtrim().

$str = '';
for($i = 1; $i <= 10; $i++){
  $str .= $i . ', ';
}
echo rtrim( $str, ', ' ); // The string is comma space

 

Link to comment
Share on other sites

mysql_fetch_array returns a numerically indexed array.  Change the call to mysql_fetch_assoc to return an associative array, which is what you want.

 

Also, with what you currently have you are repeating the entire string in each conditional body except for that comma.  Build the string before the conditional since it is the same no matter what.  Then add the comma in the special case.

 

Or use one of the methods I showed you.

Link to comment
Share on other sites

Untested

 

<?php  

  if (!$link = mysql_connect(x, x, x)) {
     echo 'Could not connect to mysql';
     exit;
  }

  if (!mysql_select_db(x, $link)) {
     echo 'Could not select database';
     exit;
  }

  $query="SELECT * FROM registry WHERE lat <> '' ORDER BY id ASC";
  $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());

  $RowStrings = Array(); // each row string will go here, this is method 2
  while ($row = mysql_fetch_array($result)) {
    // We want a string formatted like so:
    // { fld: value[, fld: value] }
    // each field happens to be named after the array keys in row so we can take
    // advantage of that fact

    $rowString = '{'; // we'll build the string for the row in here, this will
                      // be method 1
    foreach($row as $key => $value){
      $rowString .= $key . ': ' . $value . ",\n"; // method 1
      if($key == 'lat'){
        // Want lat and lng on same line
        $rowString = rtrim($rowString, "\n") . " ";
      }
    }
    $rowString = rtrim($rowString, ", \n") . '}'; // method 1
    
    // append $rowString to the $RowStrings array, for method 2
    $RowStrings[] = $rowString; // method 2
  }
  echo implode(",\n", $RowStrings); // method 2
?>

Link to comment
Share on other sites

Thanks a ton for your help, and your code DOES seem to work, but it's not what I need - I don't want to echo every column's value, the result literally must be exactly this format for Google Maps to take it:

 

{name: '$owner',
id: '$id',
location: '$location',
year: '$year',
model: '$model',
texid: '$texid',
texusername: '$texusername',
lat: '$lat', lng: '$lon'},

 

take a look at the result of your code:

 

http://registry.davelinger.com/

 

(in the head)

 

it appears to be adding in extra data and echoing stuff twice ???

With your code, it was also echoing the person's md5'd password, as well as their email and such, which obviously should not be echoed.

Link to comment
Share on other sites

Ok.  This is easily fixed.  First off, I accidentally left it as mysql_fetch_array().  Change that call to mysql_fetch_assoc().

 

As for the extra fields being displayed, change your query to select only those that you want.  Also, since the display names have to be exact, you can alias them in the query.

 

Change:

$query="SELECT * FROM registry WHERE lat <> '' ORDER BY id ASC";

to:

$query = "
  SELECT
    `owner` AS `name`,
    `id`, `location`, `year`, `texid`, `texusername`, `lat`,
    `lon` AS `lng`
  FROM registry WHERE lat <> '' ORDER BY id ASC
  ";

Also, I don't see where you're setting $model anywhere so I have no idea which field in your database lines up with model in the text you're building.

 

Finally, since what you're building here is JSON, we don't really need any fancy white spaces.

 

Try this:

<?php  

  if (!$link = mysql_connect(x, x, x)) {
     echo 'Could not connect to mysql';
     exit;
  }

  if (!mysql_select_db(x, $link)) {
     echo 'Could not select database';
     exit;
  }

  $query = "
    SELECT
      `owner` AS `name`,
      `id`, `location`, `year`, `texid`, `texusername`, `lat`,
      `lon` AS `lng`
    FROM registry WHERE lat <> '' ORDER BY id ASC
  ";
  $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());

  $RowStrings = Array(); // each row string will go here, this is method 2
  while ($row = mysql_fetch_assoc($result)) {
    // We want a string formatted like so:
    // { fld: value[, fld: value] }
    // each field happens to be named after the array keys in row so we can take
    // advantage of that fact

    $rowString = '{'; // we'll build the string for the row in here, this will
                      // be method 1
    foreach($row as $key => $value){
      $rowString .= $key . ': ' . $value . ", "; // method 1
    }
    $rowString = rtrim($rowString, ", ") . '}'; // method 1
    
    // append $rowString to the $RowStrings array, for method 2
    $RowStrings[] = $rowString; // method 2
  }
  echo implode(",\n", $RowStrings); // method 2
?>

Link to comment
Share on other sites

Oh, one other thing.  Since you're trying to create JSON you need to wrap your $value in double quotes (and also escape quotes inside).

 

Change:

    foreach($row as $key => $value){
      $rowString .= $key . ': ' . $value . ", "; // method 1
    }

 

To:

    foreach($row as $key => $value){
      if(!is_numeric($value)){
        $value = str_replace("\\", "\\\\", $value);
        $value = str_replace("\"", "\\\"", $value);
        $value = '"' . $value . '"';
      }
      $rowString .= $key . ': ' . $value . ", "; // method 1
    }

Link to comment
Share on other sites

Yah the brackets are necessary.

 

Basically the string you're creating is a handy-dandy way of creating objects in Javascript.  The square brackets are a short-hand way of creating an array in Javascript.  So the net effect of that code is to create an array of objects that Google maps uses to place the push pins on their map.

 

A word of caution.  Be sure you understand why I have the lines:

$value = str_replace("\\", "\\\\", $value);
$value = str_replace("\"", "\\\"", $value);

They may or may not be necessary depending on your data.  For the sake of argument, let's pretend that one of your name columns was:

Dave "The Coder" Linger

 

If you go ahead and just wrap that in double quotes, then your Javascript will look like this:

var businesses = [
{name: "Dave "The Coder" Linger", id: 18,

You now have a syntax error in your Javascript.  But by using str_replace we can replace a double quote in the original string with a \" which will escape the double quote properly by the time Javascript receives it.

var businesses = [
{name: "Dave \"The Coder\" Linger", id: 18,

 

Remember that the backslash is also a special character in strings which is why I have the other str_replace, which replaces a single backslash with a backslash-backslash.  The order in which you perform the replacement is also import; if you get the order wrong you will wind up with too many backslashes.

 

Again, you may or may not need to do this depending on your data, but it's important to understand what's happening there.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.