0

I am learning php and doing a small project. I have a city_name table in database with columns id, name, longitude and latitude. It might have 10-15 rows at best. Now when user load index.php I do this query to get all data from the city_name table

$city_name = mysql_query('SELECT * FROM city_name');

Values found from the above query, I want to create a javascript variable in following format. I want to do this in the same index.php inside tag.

var locations = [
    ['IMaxx', 50.780941, 6.079134],
    ['Aachen-Elisenbrunnen', 50.771680, 6.086472],
    ['Uni-Cinema', 50.776185, 6.079306],
    ['Alter-Posthof', 50.771705, 6.086561],
    ['Cinemaxx', 50.770754, 6.084942]
];

How can I do this?

asdlfkjlkj
  • 2,258
  • 6
  • 20
  • 28
  • As you're just learning PHP, it would be beneficial to you to avoid things like [mysql_ functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – SubjectCurio Nov 21 '14 at 09:12

1 Answers1

0

Simply echo it as JSON string:

<?php
$arrayFromDB = [
    ['IMaxx', 50.780941, 6.079134],
    ['Aachen-Elisenbrunnen', 50.771680, 6.086472],
    ['Uni-Cinema', 50.776185, 6.079306],
    ['Alter-Posthof', 50.771705, 6.086561],
    ['Cinemaxx', 50.770754, 6.084942]
];

echo "<script>var locations = ".json_encode($arrayFromDB).";</script>";
?>
Justinas
  • 41,402
  • 5
  • 66
  • 96