简体   繁体   中英

Transferring a multidimensional array from mysql to php to javascript

I seem to be having a bit of trouble. The PHP portion seems to work well, but I can't seem to get the info over to the JS portion. Here is what I currently have:

<!DOCTYPE html>
<html> 
  <body>
    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    mysql_connect($servername, $username, $password) or die(mysql_error());
    mysql_select_db("stuff") or die(mysql_error());
    $result = mysql_query("SELECT Location, Latitude, Longitude FROM Places WHERE Latitude IS NOT NULL GROUP BY Location, Latitude, Longitude");
    $places = array();
    while (($row = mysql_fetch_array($result, MYSQL_NUM)) !== false) {
        $places[] = $row;
    }
    ?>
    <script>
    function makeTableHTML(myArray) {
        var result = "<table border=1>";
        for(var i=0; i<myArray.length; i++) {
            result += "<tr>";
            for(var j=0; j<myArray[i].length; j++){
                result += "<td>"+myArray[i][j]+"</td>";
            }
             result += "</tr>";
        }
    result += "</table>";
    return result;
    }
    var places = "<?php echo json_encode($places) ?>";
    makeTableHTML(places);
    </script>
  </body>
</html>

I have tested the PHP portion and it works just fine. I am fairly new to the JS and I am not sure how I can go about testing/debugging this. Any help would be appreciated.

I found the makeTableHTML function on here in hopes that it would help, but I didn't have any luck.

Your PHP seems to be working. Also your javascrip HTML code generation seems to be ok. But you are no where writing the table into the DOM.

Therefore you have to select an DOM Element and write the result of makeTableHTML into it. For example:

document.getElementsByTagName("BODY")[0].innerHTML += makeTableHTML(places);

In your code example it would make more sense to generate the table with PHP directly. Javascript only make sense if you want to dynamically change your site.

I don't know what you are trying to archieve here, but maybe you should look into ajax requests. But it is hard to say, without knowing what you want to create.

You also asked about howto debug javascript, of course you could use alert() to output any variable in your code. But in more complex cases it is advisable to use the debugger. See here for howto use it in Firefox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM