Alert!!! HTML Evaluation 01- Quiz

Main Menu

PHP Loop: 016

Started by Cohort Master, May 01, 2024, 10:35 AM

Previous topic - Next topic

Cohort Master

In the following chapters you will learn how to repeat code by using loops in PHP.

Often when you write code, you want the same block of code to run over and over again a certain number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.

Loops are used to execute the same block of code again and again, as long as a certain condition is true.

In PHP, we have the following loop types:

while - loops through a block of code as long as the specified condition is true.
do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true.
for - loops through a block of code a specified number of times.
foreach - loops through a block of code for each element in an array.

The specificity of this lesson using while loop is to show you in a glance how to loop our data from database table to your webpage as an admin or controller.

Instead of going to Phpmyadmin to view if data was inserted we can call the data to our page in a tabler form.

First create your database connection using the code below and save it with

define('DB_USER','root'); // default username is root for offline server
define('DB_PASS' ,''); //password must be empty since you are working offline
define('DB_NAME''database_name'); // input your database name that you created 
$con mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
"Failed to connect to MySQL: " mysqli_connect_error();

The MySQL select function and while loop command

<th>Phone Number</th>
<th>Time Regd.</th>
"SELECT * from table_name ORDER BY 'id' ASC";
// To call all registered investors
$result mysqli_query($con$sql);
$row mysqli_fetch_array($resultMYSQLI_ASSOC))

<th><?php echo ($cnt);?></th>
<th><?php echo ($row['fullname']);?></th>
<th><?php echo ($row['email']);?></th>
<th><?php echo ($row['phone']);?></th>
<th><?php echo ($row['time']);?></th>
<?php $cnt=$cnt+1;} ?>

The above while loop will be repeating it's command once new info is being added to the database.

The information in the table above is changeable to suite your database and table info.

QuoteHow to echo time format <?php echo htmlentities($row['time']); ?>

Full code
<td><?php $go3date('d, M Y'); $v3htmlentities($row['time']); echo date('d, M Y'strtotime($v3));?></td>

To set your code to echo Active or Live if the status reports 1 else show Inactive or Block if the status reports 0.
<td><?php $suc=$row['status']; if($suc== "") { echo '<span class="text-primary">Inactive</span>'; } ?> <?php if($suc=="Credited") { echo '<span class="text-success">Credited</span>'; } ?></td>