0

I'm very new to web programming so I will try to explain my issue here! So basically I tried to get all the data from my query in PHP and push everything into an array in Javascript. The code below works for the first iteration, but it seems like after the first one, the rest just gets duplicated (it seems like the $i variable does not update?) Can someone explain to me why is that and how should I fix it? Thanks!

<?php>
  ... 
  $result = mysqli_query($con, $query);
  $num_rows = mysqli_num_rows($result);
  $i = 0;
  $history_array = array();
  if($num_rows > 0){
    while($row = mysqli_fetch_array($result)){
      array_push($history_array, $row);
    }
  }
?>

<script>
  var events = []; 
  var i = 0
  while(i< <?php echo $num_rows; ?>){
    events.push({'Date': <?php echo $history_array[$i]["Date"]; ?>, 'Title': '<?php echo 
                  $history_array[$i]["Title"]; $i++; ?>', 'Link': ''});
    i++;
  }
</script>
SN858
  • 1
  • 3
    The short answer is you can't do this. The PHP code runs on the backend (on the server), the Javascript on the frontend (in the browser). If you wish to do something like this you'll have to echo the PHP data you wish to access on the front end out in its entirely into a Javascript variable. – KLP Dec 03 '19 at 07:11
  • output the PHP variable as JSON in javascript and then iterate through it – Professor Abronsius Dec 03 '19 at 07:18

1 Answers1

0

Think of PHP as a tool that generates strings -- HTML/JS, etc. It creates a string, then sends it to the browser. Take a look at the actual string your PHP is generating, and you'll see it never actually updates $i.

You need to get PHP to generate a javascript string that your browser can use.

The easiest way to do this is to serialize your data into javascript objects using JSON, send that to the browser, and have the browser do stuff with it:

<?php
// ... generate $history_data array ...
// this creates JSON, eg: [{field1: "val1", field2: "val2", ...}, ...]
$history_data_json = json_encode($history_data);
?>

<script>
   let history_data = <?php echo json_encode($history_data)?>;
   history_data.forEach(row => { console.log(row); });
</script>
JS_Riddler
  • 1,443
  • 2
  • 22
  • 32