Define var from MYSQL data PHP

I need to define my website var from mySQL, but I don’t know how to get the data to the var. This is what I have so far.
I’m able to get the data in JSON with this:

$json_array = array();  
       while($row = mysqli_fetch_assoc($result))  
       {  
            $json_array[] = $row;  
       }  
       echo json_encode($json_array);  
       ?>  

I’m stuck in this part.

<?php   
       $connect = mysqli_connect("localhost", "user", "", "pricesdb");  
       $sql = "SELECT * FROM precios";  
       $result = mysqli_query($connect, $sql);  
       while($row = mysqli_fetch_array($result))  ?>


<script type="text/javascript">
    var websiteVars = {
            priceusd: <?php echo ''.$row['priceusd'].''?>,
            pricebs: <?php echo ''.$row['pricebs'].''?>
        };
</script>

2 Answers

You’re redefining the variable websiteVars each time through the loop.

You should keep the original loop that creates the array $json_array, and then encode the entire thing into the JavaScript variable;

var websiteVars = <?php echo json_encode($json_array); ?>;

Thank you very much, I was able to solve the problem this way.

 <?php 
  $db = mysqli_connect("localhost", "root", "", "db");  
  $sql = "SELECT * FROM precios";  
  $result = mysqli_query($db, $sql);  
  while($row=mysqli_fetch_array($result, MYSQLI_ASSOC)){ 
?> 

<script type="text/javascript">
var websiteVars = {priceUsd: <?php echo ''.$row['priceUsd'].''?>, priceBS: <?php echo ''.$row['priceBS'].''?>}; 
<?php 
  } 
?> 

</script>

Archive from: https://stackoverflow.com/questions/59057234/define-var-from-mysql-data-php

Share

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *