-3

I am trying to retrieve a set of values from a database using PHP, and then I would like to pass those retrieved values to javascript, so that they can be displayed to the user, used to construct other elements, etc.

Javascript in Index.php:

<script type="text/javascript">
;(function($) {
  $(document).ready( function() {
    var $img = $("#image1").imgNotes2({
      onReady: function() {
        var notes = [<?php include $_SERVER['DOCUMENT_ROOT'].'/home/inc/mapmarkers.php'; ?>]
        this.import(notes);
      }
    });
  });
})(jQuery);
</script>

And mapmarkers.php;

<?php

require '../assets/setup/mapdb.inc.php';
    
        $sql = "SELECT * FROM markers WHERE id >= 1;";
        $stmt = mysqli_stmt_init($conn);

        if (!mysqli_stmt_prepare($stmt, $sql)) {
            // SQL ERROR
            return false;
        }
        else {
            
            mysqli_stmt_execute($stmt);
            $results = mysqli_stmt_get_result($stmt);
            
            $index = 0;
            $string = "";
            
            while($row = mysql_fetch_assoc($results)) {
                $MarkerInfo = array(
                    'id' => $row['id'],
                    'author' => $row['author'],
                    'party' => $row['party'],
                    'permission' => $row['permission'],
                    'enabled' => $row['enabled'],
                    'xpos' => $row['xpos'],
                    'ypos' => $row['ypos']
                );
                
                echo ($MarkerInfo);
            }
        }
?>

Currently, Index.php loads and runs just fine but none of the output from mapmarkers.php is actually echoed into the script tag. What have I mucked up?

I am including mapmarkers.php because of security reasons but if there is another safe way to do this please let me know.

Looked around quite a bit and couldn't truly find anyone else with this exact problem, apologies in advance if this has already been asked/solved.

EpicPhail
  • 25
  • 3
  • 1
    use print_r or var_dump instead of echo for arrays. and you are using same key for all those array values. It will overwrite existing values – Kaushik C Jul 27 '20 at 05:12
  • Have you tried checking the page HTML source? Why are all your array keys `"id"`? – Phil Jul 27 '20 at 05:15
  • 2
    Turn on [php error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display). You are trying to echo array. Your array has same index for all values. ...? – Umair Khan Jul 27 '20 at 05:17
  • 1
    Lots of errors... 1) Your prepared statement has no parameters so `bind_param` will fail. 2) `$selector` is not defined. 3) You're overwriting `$MarkerInfo` on each loop. 4) You're using the same array key for all properties. 5) You're trying to echo an array on each loop. 6) The output will not be valid JavaScript – Phil Jul 27 '20 at 05:20
  • What helped me a lot was [this tutorial from Google about maps using PHP and MySQL](https://developers.google.com/maps/documentation/javascript/mysql-to-maps) – Pavel Janicek Jul 27 '20 at 05:25
  • I tried to make the source a little more readable, the reuse of the 'id' key was a mistake introduced in that effort. In response to Phil, As far as overwriting $MarkerInfo on each loop, it's my understanding that that is both necessary and what I want to occur, since I am hoping to retrieve an unknown amount of entries from the database, and want to add all of them to the scripts array. I also understand that it won't yet be valid javascript, I know how to solve that, but for the moment I cannot even get an echo output of any sort from mapmarkers.php. I am looking into #1 and #2 at the moment – EpicPhail Jul 27 '20 at 05:32
  • From Phil's comment, #1 and #2 can both be solved by simply removing the mysqli_stmt_bind_param line since I am not using any parameters in my SQL query - however doing so still does not result in an echo. – EpicPhail Jul 27 '20 at 05:39
  • 2
    You can't echo an array. What you should do is put all the results in a container array, e.g. `$results[] = $MarkerInfo;`. Then use `echo json_encode($results);` at the end of the loop, instead of echoing during each iteration. – Barmar Jul 27 '20 at 05:41
  • What is `mysql_fetch_assoc`? – Dharman Jul 27 '20 at 12:10

1 Answers1

0

Change your JS so it doesn't wrap the include in square brackets:

<script type="text/javascript">
;(function($) {
  $(document).ready( function() {
    var $img = $("#image1").imgNotes2({
      onReady: function() {
        var notes = <?php include $_SERVER['DOCUMENT_ROOT'].'/home/inc/mapmarkers.php'; ?>;
        this.import(notes);
      }
    });
  });
})(jQuery);
</script>

Then change the PHP script so it echoes all the results as JSON, which will be a valid JavaScript literal.

<?php

require '../assets/setup/mapdb.inc.php';
    
$sql = "SELECT * FROM markers WHERE id >= 1;";
$stmt = mysqli_stmt_init($conn);

if (!mysqli_stmt_prepare($stmt, $sql)) {
    // SQL ERROR
    return false;
}
else {
    
    mysqli_stmt_execute($stmt);
    $results = mysqli_stmt_get_result($stmt);
    
    $index = 0;
    $string = "";
    $results = [];
    while($row = mysql_fetch_assoc($results)) {
        $MarkerInfo = array(
            'id' => $row['id'],
            'author' => $row['author'],
            'party' => $row['party'],
            'permission' => $row['permission'],
            'enabled' => $row['enabled'],
            'xpos' => $row['xpos'],
            'ypos' => $row['ypos']
        );
        
        $results[] = $MarkerInfo;
    }
    echo json_encode($results);
}
?>
Barmar
  • 596,455
  • 48
  • 393
  • 495
  • I did exactly as is outlined here and in the comments on the OP in regards to encoding using json_encode with an added $results[] container array - however nothing has changed. The resulting script tag has only code in it up until the – EpicPhail Jul 27 '20 at 14:22
  • Check your PHP error log to make sure it's finding all the include files. – Barmar Jul 27 '20 at 14:27