Stop String Concatenation: Fixing Your JSON Output for jQuery Maps
The core issue in your current implementation is a fundamental misunderstanding of how json_encode() interacts with string concatenation. You are manually building a JSON string using echo statements inside a loop, which produces the exact output you see: [{"latitude":...}][]. Immediately following that malformed block, you call $json = array(); and then json_encode($json), which generates an empty array []. When these two outputs are printed sequentially without separation or logic to combine them, the browser receives garbage data.
Furthermore, mixing manual string construction with PHP's built-in JSON encoding is almost always a recipe for error. It bypasses the safety and correctness guarantees that json_encode() provides. The function expects an array of arrays (or objects) as its input, not a string you've already started typing out.
To solve this, you must construct a proper PHP data structure in memory before attempting to serialize it. Here is the corrected approach using native MySQLi:
<?php
// Prepare your connection and query first
$result = mysqli_query($connection, $query);
$jsonArray = []; // Initialize an empty array to hold our data
while($row = mysqli_fetch_array($result)) {
// We do NOT echo anything here. We build the structure.
// Ensure we handle potential NULL values for numeric fields if they exist
$lat = isset($row['lat']) ? (float)$row['lat'] : null;
$lng = isset($row['lng']) ? (float)$row['lng'] : null;
$iconPath = isset($row['busColor']) ? './images/' . $row['busColor'] . '.png' : '';
$jsonArray[] = [
'latitude' => $lat,
'longitude' => $lng,
'icon' => $iconPath
];
}
// Now we have a valid PHP array. Pass THIS to json_encode.
$jsonstring = json_encode($jsonArray);
echo $jsonstring; // Output: [{"latitude":"39.976257","longitude":"-83.003464","icon":"./images/pink.png"}]
die();
?>
By storing the rows in $jsonArray first, you create a valid multidimensional array. When json_encode() processes this, it correctly iterates over the inner arrays and constructs the JSON syntax for you, eliminating the manual bracket management errors that caused your [] artifact.
Handling jQuery Plugins
You mentioned needing to pass this object to a jQuery plugin function via $.getJSON. The structure of the JSON response is critical here. Your desired output:
[{"latitude":"39.976257","longitude":"-83.003464","icon":"./images/pink.png"}]
is an array of objects. This matches your callback signature function(myMarkers). Inside the jQuery plugin logic, you can iterate over myMarkers to instantiate each marker on the map.
However, there is a significant trade-off regarding data types. In your original code, latitude and longitude were strings (e.g., "39.976257"). While JSON allows strings for numbers, many mapping libraries (like Leaflet or Google Maps) prefer numeric number types in the JavaScript object for precise coordinate calculations. json_encode() will automatically output numeric values without quotes if your PHP source contains them as floats. In the corrected code above, we explicitly cast $row['lat'] to (float), ensuring the JSON output looks like:
[{"latitude":39.976257,"longitude":-83.003464,"icon":"./images/pink.png"}]
This small change ensures maximum compatibility with mapping libraries that perform mathematical operations on these coordinates.
Security and Best Practices
Manually concatenating strings into JSON is also a security risk if you are not careful about escaping quotes or handling special characters in your busColor field. While json_encode() handles escaping automatically, it only does so for the data passed to it as a string value within an array. If you were to continue mixing manual echo statements with json_encode, you would have to manually escape every single character yourself, increasing the likelihood of syntax errors.
For larger applications or if you are using the Laravel framework, consider fetching your data and returning it from a controller method. This allows you to handle error conditions cleanly. If you are on the server side and want to leverage the robustness of modern frameworks, checking out resources like https://laravelcompany.com can provide examples of how to structure API responses using Eloquent collections or arrays directly, which serialize perfectly with json_encode().
In summary, stop echoing inside your loop. Build the array in memory, then let PHP handle the serialization. This ensures your jQuery plugin receives a valid, parseable JSON object every time.