0

I am trying to get the values of PHP Array in JavaScript variable. Here is my code:

    $qry="select * from optin";
    $rlt1=mysql_query($qry);
    $em_ary=array();
    while($row= mysql_fetch_array($rlt1)){
        $em_ary=$row;
        echo $em_ary['timer'];}// this echo show all records that I have in data base and I want to get all the values in Javascript


<script>
    var tmr=[];
    tmr='<?php echo json_encode($em_ary['timer']); ?>';
    alert(tmr);// this alert only shows the last record in the database 
<?script>

Where I am going wrong or is there any other way to accomplish this? Thanks in advance!

Bud Damyanov
  • 30,171
  • 6
  • 44
  • 52
Rajeet
  • 37
  • 1
  • 8

2 Answers2

0

You are overwriting values within your $em_ary array in order to make an array of values you need to place [] after $em_ary which will result you an array

$em_ary[]=$row;

You need to update this also from

tmr='<?php echo json_encode($em_ary['timer']); ?>';

into

tmr="<?php echo json_encode({$em_ary['timer']}); ?>";
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
0

You need to update this line:

$em_ary = $row;

and change it to:

$em_ary[] = $row;

You are overwriting the array each time you want to add a new element to it.

Then, in the JS part, update this line:

tmr = '<?php echo json_encode($em_ary['timer']); ?>';

to:

tmr = JSON.parse('<?php echo json_encode($em_ary); ?>');

Hope this helps! Cheers!

Romi Halasz
  • 1,949
  • 1
  • 13
  • 23