如何在同一页面内的while循环之外传递php变量

I have faced small problem regarding passing php variable outside of PHP loop. I have created table and form in same page. First table is displayed and the through edit link in form pop up dialog box appears. I want to pass dynamic ID to dialog box after click edit link. My page includes a php table and form.

PHP/HTML Table

<table>
    <th>ID</th>
    <th>Title</th>
    <th>Edit</th>
        <?php
            $query="select * from video order by id desc";
            $result=$con->query("SELECT * FROM video ORDER by id DESC") or die($con->error);
            while($row=$result->fetch_assoc()){
                $id=$row['id'];
                $heading=$row['heading'];
        ?>
    <tr>
        <td>
            <?php echo $id ?>
        </td>
        <td>
            <?php echo $heading ?>
        </td>
        <td>
            <a href="#modal2" id="pop_button">Edit</a>
        </td>
        </tr>
        <?php } ?>
</table>

After this table, I want to display data in this form

PHP Form in dialog box

<div class="remodal" data-remodal-id="modal2" role="dialog" aria-labelledby="modal2Title" aria-describedby="modal2Desc">
    <form action="" method="POST" enctype="multipart/form-data">
        <table>
        <tr>
            <th>Video ID</th>
            <td>
                <input type="number" value="<?php echo $id?>" name="id" readonly></input>
            </td>
        </tr>
        <tr>
            <th>Video Title</th>
            <td>
                <input type="text" value="<?php echo $heading?>" name="title"></input>
            </td>
        </tr>
        </table>    
    </form> 
</div>

I know that while loop can't connect to popup dialog box form, so my code prints only data of first row. If I include whole code within while loop, my table structure become mess. Is there any idea to pass ID outside of while loop ? I tried using global variable method, but it doesn't work. Perhaps I can't properly use global variable. Thanks

In your while loop store values in to array like this:

<?php
            $query="select * from video order by id desc";
            $result=$con->query("SELECT * FROM video ORDER by id DESC") or die($con->error);
            $array = [];            
            while($row=$result->fetch_assoc()){
                $id=$row['id'];
                $heading=$row['heading'];
                $array[$id] = $heading;

        ?>

And in your html table like this :

    <table>
            <tr>
                <th>Video ID</th>
                <th>Video Title</th>
                <?php foreach ($array as $key => $val){ ?>
                <td>
                    <input type="number" value="<?php echo $key?>" name="id" readonly></input>
                </td>
                <td>            
                    <input type="text" value="<?php echo $val?>" name="title"></input>
                </td>           
                <?php } ?>
            </tr>
  </table>