How To Use Foreach Get Data From The Database Table --
My database has a table called tblprojects with column names say, project_num, project_status, project_name. I want to use foreach loop to get the data from the database and displa
Solution 1:
The foreach
not needed here.
<?php
$projects = array();
while ($project = mysql_fetch_assoc($records))
{
$projects[] = $project;
}
foreach ($projects as $project)
{
?>
<tr>
<td><?php echo $project['proj_name']; ?></td>
<td><?php echo $project['proj_num']; ?></td>
<td><?php echo $project['proj_status']; ?></td>
</tr>
<?php
}
?>
Solution 2:
<?php
// fetch data from the database
$records = mysql_query('select project_num, project_status, project_name from tblprojects') or die("Query fail: " . mysqli_error());
?>
<table class="table table-striped table-condensed" id="tblData">
<thead>
<tr>
<th>Project Name</th>
<th>Project Number</th>
<th>Project Status</th>
</tr>
</thead>
<tbody>
<?php
//records as in an array
foreach( $records as $data ) // using foreach to display each element of array
{
echo "<tr><td>".$data['proj_name']."</td>
<td>".$data['proj_num']."</td>
<td>".$data['proj_status']."</td>
</tr>";
}
?>
</tbody>
</table>
Solution 3:
Hello Try this code you have not need to foreach loop so it's save your time and good practice in future
<?php
$projects = array();
while ($project = mysql_fetch_assoc($records))
{
?>
<tr>
<td><?php echo $project['proj_name']; ?></td>
<td><?php echo $project['proj_num']; ?></td>
<td><?php echo $project['proj_status']; ?></td>
</tr>
<?php
}
?>
Post a Comment for "How To Use Foreach Get Data From The Database Table --"