This is how I got PHP foreach loop working in HTML table. You can find the working code below. Get all the code for PHP Connect to MySQL Database, using mysqli api.
PHP foreach Loop
PHP foreach loop iterates through the array, associative array, MySQL table, and also lets run arithmetic operators.
Download PHP 7 eBook For Free
php foreach array iteration
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
echo $value;
}
// 1, 2, 3, 4
php foreach array iteration with arithmetic expression
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// 2, 4, 6, 8
php foreach associative array iteration
$arr1 = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($arr1 as $key => $value) {
echo "$key => $value "."<br>";
}
// echo output
// one => 1
// two => 2
// three => 3
// seventeen => 17
PHP foreach Loop in HTML table
<table>
<thead>
<tr>
<th>ID</th>
<th>Brand</th>
<th>Model</th>
<th>Year</th>
<th>Category</th>
<th>Gender</th>
<th>Color</th>
<th>Weight KG</th>
</tr>
</thead>
<tbody>
<tr>
// PHP foreach Loop
<?php foreach ($bicycles as $bicycle){ ?>
<td> <?php echo $bicycle['id']; ?> </td>
<td> <?php echo $bicycle['brand']; ?> </td>
<td> <?php echo $bicycle['model']; ?> </td>
<td> <?php echo $bicycle['year']; ?> </td>
<td> <?php echo $bicycle['category']; ?> </td>
<td> <?php echo $bicycle['gender']; ?> </td>
<td> <?php echo $bicycle['color']; ?> </td>
<td> <?php echo $bicycle['weight_kg']; ?> </td>
</tr>
<?php } ?>
</tbody>
</table>
PHP Connect to MySQL Database
MySQL Database Connection, Query, & php foreach loop
<?php
// STEP ONE
// // database credentials
$hostname = 'localhost';
$dbname = 'databse_name';
$dbuser = 'user_name';
$dbpass = 'user_password';
// STEP TWO : connecting to the database
$mysqli = new mysqli($hostname, $dbuser, $dbpass, $dbname);
// STEP THREE : SQL query
$bicycles = $mysqli->query('SELECT * FROM bicycles');
?>
// STEP FOUR : Displaying table values through HTML Table
<table>
<thead>
<tr>
<th>ID</th>
<th>Brand</th>
<th>Model</th>
<th>Year</th>
<th>Category</th>
<th>Gender</th>
<th>Color</th>
<th>Weight KG</th>
</tr>
</thead>
<tbody>
<tr>
<?php foreach ($bicycles as $bicycle){ ?>
<td> <?php echo $bicycle['id']; ?> </td>
<td> <?php echo $bicycle['brand']; ?> </td>
<td> <?php echo $bicycle['model']; ?> </td>
<td> <?php echo $bicycle['year']; ?> </td>
<td> <?php echo $bicycle['category']; ?> </td>
<td> <?php echo $bicycle['gender']; ?> </td>
<td> <?php echo $bicycle['color']; ?> </td>
<td> <?php echo $bicycle['weight_kg']; ?> </td>
</tr>
<?php } ?>
</tbody>
</table>
Download PHP 7 eBook For Free
PHP YouTube Clone App Course
If you are looking for a PHP course that is also highly rated, here you go.