js变量在php里面循环[重复]

js变量在php里面循环[重复]

问题描述:

This question already has an answer here:

I am familiar with php but still learning Js. Some people helped me on completing a ajax form to send data to mysql. But now I am stuck on below:

I used while loop as I want to print every thing which matches query

while($row = mysqli_fetch_assoc($result))
{
     comment_id = $row['comment_id'];
     echo "<script>";
     echo "var count = ".json_encode($comment_id);
      echo "</script>";
    }

But what I get a last value on while loop is assigned to js variable count as php is server sided and js is client sided. Then I tried adding array (as it can hold many values)

    while($row = mysqli_fetch_assoc($result)) 
{
    $comment_id = $row['comment_id'];
     echo "<script>";
                                    echo "var count = [];";
                                    echo.     "count.push($com);";
                                    echo "</script>"; 
}

But again i am getting last value in while loop. Is there any way I can assign whole data inside a php while loop to js variable.

Thanks :)

</div>

I just got an idea and I think it is now resolved. I did is taken a php array inside while loop and assigned it to js array.

    $count = [];
    while($row = mysqli_fetch_assoc)
    $comment_id = $row['comment_id'];
     array_push($count,$comment_id);
    echo "<script>";
    echo "var count =".json_encode($count);
    echo "</script>";
}