Reputation: 749
I have a code like this.
<?php
$book_query = mysql_query("select * from book_master')");
while($book_query_fetch = mysql_fetch_assoc($book_query)){
echo "<pre>";
print_r($book_query_fetch);
echo "</pre>"
}
?>
Array
(
[Book_Name] => Book1
[Book_ID] => 123
)
Array
(
[Book_Name] => Book2
[Book_ID] => 124
)
Book Name Book_ID
Book1 123
Book2 124
How can I achieve this? EDIT: The header part is a dynamic load. so i need the table header also in a loop
Upvotes: 0
Views: 311
Reputation: 26421
I don't know where you stuck doing that, but you can do below,
echo "<table>";
$i = 0;
while($row = mysql_fetch_assoc($book_query))
{
if($i == 0){
$columns = array_keys($row);
echo "<th>";
foreach($columns as $column){
echo "<td> $column</td>";
}
echo "</th>";
}
echo'<tr>';
echo '<td>'.$row['Book_Name'].'</td>';
echo '<td>'.$row['Book_ID'].'</td>';
echo '</tr>';
$i++;
}
echo "</table>";
Waring: Please, don't use mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Upvotes: 2
Reputation: 86
//try this
<?php
$book_query = mysql_query("select * from book_master')");
while($book_query_fetch = mysql_fetch_assoc($book_query)){
echo "<pre>";
$a="<table><tr>";
foreach ($book_query_fetch as $key=>$value){
$a="<th>".$key."</th>"
}
exit;
}
$a="</tr>"
while($book_query_fetch = mysql_fetch_assoc($book_query)){
$a="<tr>";
foreach ($book_query_fetch as $key=>$value){
$a="<td>".$value."</td>"
}
$a="</tr>";
}
$a="</table>"
echo $a;
?>
Upvotes: 0
Reputation: 10111
Try this
while($row = mysql_fetch_assoc($book_query))
{
echo'<tr><th>'.
$columns = array_keys($row);
foreach($columns as $column){
echo "<td> $column</td>";
}
.'</th></tr><tr>';
echo '<td>'.$row['Book_Name'].'</td>';
echo '<td>'.$row['Book_ID'].'</td>';
echo '</tr>';
}
echo "</table>";
Upvotes: 0
Reputation: 1796
you can do this
<table>
<?php
$book_query = mysql_query("select * from book_master')");
$book_query_fetch = mysql_fetch_assoc($book_query); ?>
<th>
<td><?php echo $book_query_fetch['book_name']; ?></td>
<td><?php echo $book_query_fetch['Book_ID']; ?> </td>
</th>
<?php while($book_query_fetch){ ?>
<tr>
<td><?php echo $book_query_fetch['Book_Name']; ?></td>
<td><?php echo $book_query_fetch['Book_ID']; ?></td>
</tr>
<?php } ?>
</table>
Upvotes: 0
Reputation: 685
Along with Rikesh's code, Use the array_keys() function. this will fetch all the keys of the subset array.
So you can fetch the keys also dynamically.
Hope this helps you.
Upvotes: 0
Reputation: 1166
Try this-
<?php
$book_query = mysql_query("select * from book_master')");
echo "<table>";
echo"<tr><td>Book Name</td><td>Book_ID</td></tr>";
while($book_query_fetch = mysql_fetch_assoc($book_query)){
echo"<tr><td>".$book_query_fetch['Book_Name']."</td><td>".$book_query_fetch['Book_ID']."</td></tr>";
}
echo "</table>";
?>
Upvotes: 0