Using Javascript I need to get some rows from a DB table, and then loop through each row and use different fields from each row.
For example, if I get the rows like this:
var coordinatesArray = '<?php
global $wpdb;
开发者_开发知识库 echo $wpdb->get_var("SELECT * FROM users_coordinates WHERE lat>20 and lat<40 and long>-10 and long<40);
?>';
How should I write the following code:
// for each row do: {
// alert the id field
// alert the lat field
// alert the long field
// }
JSON is the way to put the output in, that ensures that the result will be valid JavaScript and protects you from arbitrary code execution in JS.
var coordinatesArray = <?php
global $wpdb;
// replace * by id, lat and long since you don't need other fields
$sql = "SELECT id, lat, long FROM users_coordinates WHERE lat>20 and lat<40 and long>-10 and long<40";
$rows = $wpdb->get_results($sql);
// if the function fails (?), make valid JS syntax
if (is_array($rows)) {
echo json_encode($rows);
} else {
echo '[]';
}
?>;
for (var i=0; i<coordinatesArray; i++) {
alert(coordinatesArray[i].id);
alert(coordinatesArray[i].lat);
alert(coordinatesArray[i]["long"]);
}
The other way would be creating a JS object with the id
field as key of the JS object:
var coordinatesMap = <?php
global $wpdb;
// replace * by id, lat and long since you don't need other fields
$sql = "SELECT id, lat, long FROM users_coordinates WHERE lat>20 and lat<40 and long>-10 and long<40";
// note: OBJECT_K, the result will be an associative array with the first field of a
// row as key
$rows = $wpdb->get_results($sql, OBJECT_K);
// if the function fails (?), make valid JS syntax
if (is_array($rows)) {
echo json_encode($rows);
} else {
echo '{}';
}
?>;
for (var id in coordinatesMap) {
if (coordinatesMap.hasOwnProperty(id)) {
alert(id);
alert(coordinatesMap[id].lat);
alert(coordinatesMap[id]["long"]);
}
}
Please replace alert
by something else, it's not really user-friendly. Remember that PHP != JavaScript and you cannot use PHP functions in JavaScript and vice versa. If you're not sure how the output would look like, use the View source option of a page.
References:
- http://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results
You may have a better time writing your own custom PHP script to fetch these values (rather than depending on WP), loop through them, and build a json object that you return to the javascript.
First, $wpdb->get_var can only get one value. http://codex.wordpress.org/Class_Reference/wpdb#SELECT_a_Variable
Use $wpdb->get_results instead http://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results
var coordinatesArray = '<?php
global $wpdb;
echo $wpdb->get_results("SELECT * FROM users_coordinates WHERE lat>20 and lat<40 and long>-10 and long<40);
?>';
for(coord in coordinatesArray) {
alert(coordinatesArray[coord].id);
alert(coordinatesArray[coord].lat);
alert(coordinatesArray[coord].long);
}
I haven't tested, but it should be something like that.
精彩评论