Skip to content

Instantly share code, notes, and snippets.

@pjehan
Last active August 29, 2015 14:01
Show Gist options
  • Save pjehan/e5ea8c1d38d9b844d57c to your computer and use it in GitHub Desktop.
Save pjehan/e5ea8c1d38d9b844d57c to your computer and use it in GitHub Desktop.
Create a javascript array from an SQL query using PHP
<?php
// Search for the latitude and longitude in the database
$query = mysqli_query($con,"SELECT lat, `long` FROM shop");
// String used to store the javascript array
$locations = '';
$i = 0;
while ($row = mysqli_fetch_array($query)) {
$lat = $row["lat"];
$long = $row["long"];
// If this is not the first loop, we add a comma after the previous array
if($i != 0) {
$locations .= ',';
}
// Append the array to the string
$locations .= '[' . $lat . ',' . $long . ']';
$i++;
}
?>
<script>
// Create the javascript array from the PHP string
var locations = [<?php echo $locations; ?>];
console.log(locations);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment