PHP Scripts – WordPress Tutorials

Most of us using A to Z sorting in our project while filtering data. Let’s suppose i have penality if users in my database and i want to fiter them on the base of alphabets.

Situation is if i click “A” it should display all records related to A, If a Click “N” it should display all records starting with “N”.

Demo                                                                  Download Code

To do this we have to follow the few steps.

1- Create A to Z Hyperlinks so they could help us to filter the records. To do this i am using range() function that will create the following URL’s:

a-to-z-sorting-list-php

Code to create this is :

1
2
3
4
5
6
foreach (range('A', 'Z') as $i)
{

echo '<a href="index.php?alphabet='.$i.'">'.$i.'</a> | ';

}

2-  Now we have created links for A to Z alphabets filteration.

a-to-z-sorting-in-php

We need to fetch data from the database to display all records Once. And change that query if alphabet is set then sort records on the base of that alphabet. TO do this we have the following code.

1
2
3
4
5
6
7
8
9
10
$alphabet    =    $_GET['alphabet'];
if($alphabet)
{
$query    =    "SELECT * FROM users WHERE firstname LIKE '".$alphabet."%' ORDER BY firstname";
}
else
{
$query    =    "SELECT * FROM users ORDER BY firstname";
}
$res    =    mysql_query($query);

Now we have set the query distinction too, Next step is to display records that are filtered. Here is the code for this section as well:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<table align="center">
<tr>
<th>First Name</th><th>Second Name</th>
</tr>
<?php
if(mysql_num_rows($res)>0)
{
while($row=mysql_fetch_array($res))
{
?>
<tr>
<td><?php echo $row['firstname'];?></td><td><?php echo $row['secondname'];?></td>
</tr>

<?php
}
}
else
{
?>
<h3 style="color:#F00;margin-left: 348px;">We Have No Results for Alphabet starting with "<?php echo $_REQUEST['alphabet'];?>"</h3>
<?php
}
?>
</table>

Demo                                                                  Download Code

Hope you would like this, please show your interest in Comments section.

Random Posts


Categories: PHP, Web Development
  • Shahbaz Ahmed Bhatti

    COOOOOOOOOOl NICE WORK. i M GOING SUBCRIBE Your Blog