PHP get data from database, and use it outside while loop

11,570

Solution 1

You don't have to use a while loop. You can fetch the data as you need it.

$row1 = mysql_fetch_array($qry);
$row2 = mysql_fetch_array($qry);

I don't like doing this though because you have to keep track of the resource ($qry in this case) and you have to keep typing mysql_fetch_*() so I tend to load results into an array before I use them.

$result = array();
while($row=mysql_fetch_object($qry))
{
    $result[] = $row;
}

Solution 2

Build the table inside your loop, and then echo it to the page. For example, if you were building a table where each row had a user's ID and name, it would look like this:

$table = "";
while($row=mysql_fetch_array($qry)) {   
   $tablerow = "<tr><td>" . $row['id'] . "</td><td>" . $row['name'] . "</td></tr>";
   $table .= $tablerow;
}   

// you've built a string with the entire table. Now write it to the page.
echo($table);

Building your table outside the while loop is usually a bad idea, because you're repeating a lot of code and you don't know how many rows you need to put in. But if you really want to do it the way you showed in your question (maybe because you only want certain specific rows from the query?), build an array in your while loop and then refer to that array outside of it.

$results = array();
while($row=mysql_fetch_array()) {   
    $results[] = $row;
}       

Then you can use <td><?php echo($results[0]['id']) ?></td> to write a cell with the first user's ID number, and so forth.

Share:
11,570
Fakhr Alam
Author by

Fakhr Alam

Updated on June 26, 2022

Comments

  • Fakhr Alam
    Fakhr Alam almost 2 years
    <?php   
    $q=select * from students where (dynamic for user searching)   
    $qry=mysql_fetch_array($q);   
    while($row=mysql_fetch_array())   
    {   
       **// i do not need data here?**   
    }   
    ?>   
    < table>   
    < tr>< td><?php echo **$row[?][?];** ?>< /td>< td><?php echo **$row[?][?];** ?>< /td>...< /tr>   
    < tr>< td><?php echo **$row[?][?];** ?>< /td>< td><?php echo **$row[?][?];** ?>< /td>...< /tr>   
    ....    
    < /table> 
    

    In need to generate a dynamic report in html table format the html table rows and columns are static for results so i cant use echo with in while loop i have to access it out side while loop i have an idea of selecting single row single column for each cell of table separatly but it will be time consuming and length any alternative or solution?