Saturday, October 15, 2016

How to filter data from a MySQL Database Table with PHP Function





Here if we want to filter data from above table.
First we will use a function which will use to get the data in array formate as following

<?php

function leaders($mysqli)
{
$arr = array();

if($stmt = $mysqli->prepare("SELECT firstname, lastname, pts FROM members ORDER BY pts DESC LIMIT 20"))
{
$stmt->execute();
$stmt->bind_result($firstname, $lastname, $pts);
while($stmt->fetch())
{
$arr[] = $firstname;
$arr[] = $lastname;
                    $arr[] = $pts;
}

return $arr;
}
}

?>

For displaying data we will use the following code.

<table width="100%" border="1" align="center"  bgcolor="#f0f0f0" id="member_table">
<tr bgcolor="#cf4c3f">
<td colspan="10" align="center">
<h2>Members</h2></td>
</tr>
<tr>
<th>Rank</th>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
    
<?php
    
  $leaders = leaders($mysqli);
 

       $rank = 0;
$leadcount = 0;
$leaddatacount = count($leaders);
for($i=0;$i<$leaddatacount;$i++)
{
$leadcount++;
if($leadcount==1) // Firstname
{
                    
                    $rank++;
echo "<tr><td>". $rank ."</td><td>". $leaders[$i] . "</td>";
}
elseif($leadcount==2) // Lastname
{
echo "<td>" .$leaders[$i]. "</td>";
}
                elseif($leadcount==3) // Points
                {
                    
                    echo "<td>" .$leaders[$i]. "</td></tr>";
                    
                    $leadcount = 0;
                    
                }
}
    

   ?>
    
</table>
Share:

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *