What's new
  • Welcome to PHCorner Forums. Take a moment to Sign up and gain unlimited access and extra privileges that guests are not entitled to, such as: All that and more! Registration is quick, simple and absolutely free. Join our community today!

Tutorial PHP - Simple Sort Column

lilpatotie

Addict
Established
Joined
Sep 29, 2017
Messages
470
Reaction score
63
Age
31



In this tutorial we will create a Simple Sort Column using PHP. This code will arrange the table data in a sortable way by changing to ascending to descending. This code use MySQLi ORDER BY by adding a parameter ASC or DESC to change the arrangement of data in the table list.This is a user-friendly kind of program feel free to modify it.
We will be using PHP as a scripting language that manage a database server to handle a bulk of data per transaction. It describe as an advance technology that manage both server and control-block of your machine.

Getting Started:
First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server You must register or login to view this..
And this is the link for the jquery that i used in this tutorial You must register or login to view this..
Lastly, this is the link for the bootstrap that i used for the layout design You must register or login to view this..

Creating Database
Open your database web server then create a database name in it db_sort, after that click Import then locate the database file inside the folder of the application then click ok.
tut1


Creating the database connection
Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.

  1. <?php
  2. $conn = You must register or login to view this.("localhost", "root", "", "db_sort");
  3. if(!$conn){
  4. You must register or login to view this.("Error: Failed to connect to database!");
  5. }
  6. ?>


Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as index.php.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5. <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
  6. </head>
  7. <body>
  8. <nav class="navbar navbar-default">
  9. <div class="container-fluid">
  10. <a class="navbar-brand" href="<a href="You must register or login to view this.">Sourcecodester</a>
  11. " rel="nofollow">You must register or login to view this.">Sourcecodester</a>
  12. </a> </div>
  13. </nav>
  14. <div class="col-md-3"></div>
  15. <div class="col-md-6 well">
  16. <h3 class="text-primary">PHP - Simple Sort Column</h3>
  17. <hr style="border-top:1px dotted #ccc;"/>
  18. <button type="button" class="btn btn-success pull-right" data-toggle="modal" data-target="#form_modal"><span class="glyphicon glyphicon-plus"></span> Add employee</button>
  19. <br /><br />
  20. <form method="POST" action="">
  21. <button class="btn btn-primary" name="asc"><span class="glyphicon glyphicon-arrow-up"></span> Ascending</button>
  22. <button class="btn btn-danger" name="desc"><span class="glyphicon glyphicon-arrow-down"></span> Descending</button>
  23. </form>
  24. <br /><br />
  25. <?php include 'sort.php'?>
  26. </div>
  27. <div class="modal fade" id="form_modal" aria-hidden="true">
  28. <div class="modal-dialog">
  29. <div class="modal-content">
  30. <form action="add.php" method="POST">
  31. <div class="modal-header">
  32. <h3 class="modal-title">Add Employee</h3>
  33. </div>
  34. <div class="modal-body">
  35. <div class="col-md-2"></div>
  36. <div class="col-md-8">
  37. <div class="form-group">
  38. <label>Firstname</label>
  39. <input type="text" name="firstname" class="form-control" required="required"/>
  40. </div>
  41. <div class="form-group">
  42. <label>Lastname</label>
  43. <input type="text" name="lastname" class="form-control" required="required"/>
  44. </div>
  45. <div class="form-group">
  46. <label>Position</label>
  47. <input type="text" name="position" class="form-control" required="required"/>
  48. </div>
  49. </div>
  50. </div>
  51. <br style="clear:both;"/>
  52. <div class="modal-footer">
  53. <button type="button" class="btn btn-danger" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Close</button>
  54. <button class="btn btn-primary" name="add" ><span class="glyphicon glyphicon-save"></span> Save</button>
  55. </div>
  56. </form>
  57. </div>
  58. </div>
  59. </div>
  60. <script src="js/jquery-3.2.1.min.js"></script>
  61. <script src="js/bootstrap.js"></script>
  62. </body>
  63. </html>

Creating PHP Query
This code contains the php query of the application. This code will save the employee data inputs to the MySQLi database server. To do that just copy and write this block of codes inside the text editor, then save it as add.php.

  1. <?php
  2. require_once 'conn.php';
  3. if(You must register or login to view this.($_POST['add'])){
  4. $firstname = $_POST['firstname'];
  5. $lastname = $_POST['lastname'];
  6. $position = $_POST['position'];
  7. You must register or login to view this.($conn, "INSERT INTO employee VALUES('', '$firstname', '$lastname', '$position')") or You must register or login to view this.(You must register or login to view this.());
  8. You must register or login to view this.("location: index.php");
  9. }
  10. ?>

Creating the Main Function
This code contains the main function of the application. This code will sort the data in the table when the button is clicked. To make this just copy and write these block of codes below inside the text editor, then save it as sort.php

  1. <?php
  2. require 'conn.php';
  3. ?>
  4. <table class="table table-bordered">
  5. <thead class="alert-info">
  6. <tr>
  7. <th>Firstname</th>
  8. <th>Lastname</th>
  9. <th>Position</th>
  10. </tr>
  11. </thead>
  12. <tbody>
  13. <?php
  14. if(You must register or login to view this.($_POST['asc'])){
  15. $query = You must register or login to view this.($conn, "SELECT * FROM employee ORDER BY lastname ASC") or You must register or login to view this.(You must register or login to view this.());
  16. while($fetch = You must register or login to view this.($query)){
  17. echo "<tr>
  18. <td>".$fetch['firstname']."</td>
  19. <td>".$fetch['lastname']."</td>
  20. <td>".$fetch['position']."</td>
  21. </tr>";
  22. }
  23. }else if(You must register or login to view this.($_POST['desc'])){
  24. $query = You must register or login to view this.($conn, "SELECT * FROM employee ORDER BY lastname DESC") or You must register or login to view this.(You must register or login to view this.());
  25. while($fetch = You must register or login to view this.($query)){
  26. echo "<tr>
  27. <td>".$fetch['firstname']."</td>
  28. <td>".$fetch['lastname']."</td>
  29. <td>".$fetch['position']."</td>
  30. </tr>";
  31. }
  32. }else{
  33. $query = You must register or login to view this.($conn, "SELECT * FROM employee") or You must register or login to view this.(You must register or login to view this.());
  34. while($fetch = You must register or login to view this.($query)){
  35. echo "<tr>
  36. <td>".$fetch['firstname']."</td>
  37. <td>".$fetch['lastname']."</td>
  38. <td>".$fetch['position']."</td>
  39. </tr>";
  40. }
  41. }
  42. ?>
  43. </tbody>
  44. </table>

There you have it we successfully created Simple Sort Column using PHP. I hope that this simple tutorial help you to what you are looking for. Enjoy Coding!

NOTE: I don't own this tutorial or application. I just share this for more knowledge.
Credits to the Owner
 

pixkit

Addict
I'd prefer if we split the frontend from the backend api though so that they are:

  • not tightly couple
  • makes things simpler to read
  • makes the backend api reusable.

I'll try today to give an example of what I mean
 

aa1012

Enthusiast
it would be more sophisticated if we separate the data access and the frontend coding. it will be easier to manage, read, test and maintain in the future. It is also more secure. it would also be better if you use stored procedure or ORM in your sql queries to avoid injections and how data is persist from the database.
 
Yes. It's also open for more development and suggestions. It will always be depends to the creator. Isn't it?
 

pixkit

Addict
it would be more sophisticated if we separate the data access and the frontend coding. it will be easier to manage, read, test and maintain in the future. It is also more secure. it would also be better if you use stored procedure or ORM in your sql queries to avoid injections and how data is persist from the database.
You are mistaken. Sorry.

Whether you go with my suggestion or go with the original tutorials workflow, both are flawed security wise. Both implementations are NOT SECURED. Period. I find it comical that you think what you are saying is secured. How can you say it's secured? There's no authentication in the first place, for example. Where's the encryption and enforced security policy?

Stored procedures are thing of the past. Why put your business logic in stored procedures? You are coupling your business on a particular db implementation.

Both implementations (mine and the tutorial) are open to SQL injection. But that's the not the point I am pointing out. I am pointing out that original implementation has tight coupling and makes the backend api not reusable.

Coupling and security are two different concerns. Bad coupling though makes security solutions harder to implement. Loosely coupled systems are easier to address.
 

S01T004718

Enthusiast
add.php line 5-7 is a waste of space, line 9 is vulnerable for sql injection, use parameter binding instead.
 

pixkit

Addict
add.php line 5-7 is a waste of space, line 9 is vulnerable for sql injection, use parameter binding instead.
Well to be fair, most of tutorials like this one are just meant to be just a general tutorial. Security is really up to the person or team implementing the solution -- otherwise the tutorial will be huge if it's gonna cover everything. But you do bring a good point so for someone to say this pattern in the tutorial is more secure is indeed a myth.
 

aa1012

Enthusiast
You are mistaken. Sorry.

Whether you go with my suggestion or go with the original tutorials workflow, both are flawed security wise. Both implementations are NOT SECURED. Period. I find it comical that you think what you are saying is secured. How can you say it's secured? There's no authentication in the first place, for example. Where's the encryption and enforced security policy?

Stored procedures are thing of the past. Why put your business logic in stored procedures? You are coupling your business on a particular db implementation.

Both implementations (mine and the tutorial) are open to SQL injection. But that's the not the point I am pointing out. I am pointing out that original implementation has tight coupling and makes the backend api not reusable.

Coupling and security are two different concerns. Bad coupling though makes security solutions harder to implement. Loosely coupled systems are easier to address.
You might just missed my point sir. The only thing Id like to point out is the way or his approach in making query of data from the database. and, in general, the coding scheme he use in the above tut. There will never be a secured approach weather you use repository and unit of work pattern, weather you implement tight security management elsewhere from the network level. nor from other implementations of security. it is a far achievable. only, I am giving advise to the op to at least apply the best practices.


"Coupling and security are two different concerns. Bad coupling though makes security solutions harder to implement. " - You seemed to be contradicting from this statement brother. In the first place, we(including you), programmers are following the implementation of repository pattern and unit of work for an instance, because of not just a decoupling to underlying data persistence but also for security reasons. why would you follow such pattern for nothing when you can just implement just like op did to his tut isn't it? so for me, following these good practices means a lot to securities concern, not directly equates but it has a tight relationship.
 

maskHack

Addict
it would be more sophisticated if we separate the data access and the frontend coding. it will be easier to manage, read, test and maintain in the future. It is also more secure. it would also be better if you use stored procedure or ORM in your sql queries to avoid injections and how data is persist from the database.
Paki linaw nga to? dahil hindi ganito ang modern web architecture implementation.
1. Paano naging sophisticated ang decoupling ng frontend(UI) at data access layer / server (API)? familiar ka ba sa REST API?
2. Paano naging flexible and scalable ang ganitong design? Let's say gusto ko gumawa ng native mobile version at desktop version nung app, paano ko yun gagawin kung yung data access layer ko ay tightly coupled sa presentational layer ko? Gagawa ba ako ulit ng server at database dedicated para sa mobile device at desktop version ko?
3. If SQL injection is much of a concern, does using ORM would be enough and guarantee security from injection? note: ORM's are just db abstraction
 

aa1012

Enthusiast
Paki linaw nga to? dahil hindi ganito ang modern web architecture implementation.
1. Paano naging sophisticated ang decoupling ng frontend(UI) at data access layer / server (API)? familiar ka ba sa REST API?
2. Paano naging flexible and scalable ang ganitong design? Let's say gusto ko gumawa ng native mobile version at desktop version nung app, paano ko yun gagawin kung yung data access layer ko ay tightly coupled sa presentational layer ko? Gagawa ba ako ulit ng server at database dedicated para sa mobile device at desktop version ko?
3. If SQL injection is much of a concern, does using ORM would be enough and guarantee security from injection? note: ORM's are just db abstraction

Sorry pero ang pagkakaintindi ko kasi, a good software architecture should consists of loosely coupled components such as classes or objects. In that way, one component or object is less dependent to each other and doesnt require the other object's response or presence. Hence, equates to a scalability, flexibility and maintainability. In what way? for instance, the application encounters an error within the somewhere the components, if each component is loosely coupled, then pinning down this error would be easy and will be isolated in less tedious manner. Going back to the op's tut/sample codes, those area where the data is being gathered and sent back to the database are jammed all over the place when it is even possible to separate it using different class or object to make it easier to read and troubleshoot. Another scenario is when you need to update something from the area where the system does its user input calculations? In a tightly coupling, you will be needing to repack the entire solution just to implement the changes you've made only from those area.


Question, kung mas okay pala ang tightly coupling, paano mo implement yan sa isang malaking project? at paano kung group of dev kayo working on a 1 big project? when your components are tied and dependent together? paano ang disperse ng workload nyo?

I dont know much about the Representational State Transfer nor about SOAP.
 

maskHack

Addict
Sorry pero ang pagkakaintindi ko kasi, a good software architecture should consists of loosely coupled components such as classes or objects. In that way, one component or object is less dependent to each other and doesnt require the other object's response or presence. Hence, equates to a scalability, flexibility and maintainability. In what way? for instance, the application encounters an error within the somewhere the components, if each component is loosely coupled, then pinning down this error would be easy and will be isolated in less tedious manner. Going back to the op's tut/sample codes, those area where the data is being gathered and sent back to the database are jammed all over the place when it is even possible to separate it using different class or object to make it easier to read and troubleshoot. Another scenario is when you need to update something from the area where the system does its user input calculations? In a tightly coupling, you will be needing to repack the entire solution just to implement the changes you've made only from those area.


Question, kung mas okay pala ang tightly coupling, paano mo implement yan sa isang malaking project? at paano kung group of dev kayo working on a 1 big project? when your components are tied and dependent together? paano ang disperse ng workload nyo?

I dont know much about the Representational State Transfer nor about SOAP.
That's your claim, not mine. Let me rephrase your statement, Ang sabi mo "it would be more sophisticated if we separate the data access and the frontend coding. it will be easier to manage, read, test and maintain in the future ". - so you're encouraging tight coupling sa data layer at presentational layer as how this tutorial thread does it.

Question, kung mas okay pala ang tightly coupling, paano mo implement yan sa isang malaking project? at paano kung group of dev kayo working on a 1 big project? when your components are tied and dependent together? paano ang disperse ng workload nyo? - I should be the one asking that to you. since you encourage tight coupling of backend and frontend layers.

Pixkit and I share the same understanding with your statement that's why pixkit disagrees on you claim. Kaya ko tinatanong kase baka na mi-misunderstood ka namin.
 

pixkit

Addict
"Coupling and security are two different concerns. Bad coupling though makes security solutions harder to implement. " - You seemed to be contradicting from this statement brother. In the first place, we(including you), programmers are following the implementation of repository pattern and unit of work for an instance, because of not just a decoupling to underlying data persistence but also for security reasons. why would you follow such pattern for nothing when you can just implement just like op did to his tut isn't it? so for me, following these good practices means a lot to securities concern, not directly equates but it has a tight relationship.
I don't see where the contradiction is. Coupling and security are two different concerns. It's like designing the structure of your house versus adding security cameras and bodyguards. Both concerns can be addressed separately BUT if you design the structure of your house in a bad way, installing cameras or other security tech might be a challenge instead of being a straightforward activity.

Of course a simple house may not be such a big deal (a simple hello world program for example), but imagine a multi-room, mansion, or condo, or series of properties (imagine enterprise programs). Then your small problem has become really huge pain in the a$$.
 

pixkit

Addict
Sorry pero ang pagkakaintindi ko kasi, a good software architecture should consists of loosely coupled components such as classes or objects. In that way, one component or object is less dependent to each other and doesnt require the other object's response or presence. Hence, equates to a scalability, flexibility and maintainability.
Yes, this is true but it doesn't end with loosely coupled classes or objects. Yes, it helps in scalability, flexibility and maintainability. BUT and a BIG BUT, you are only looking at the small picture. It's like you're saying a good organization starts with a diligent and smart individual. Yes, that's true but the success of an organization needs more than just an individual person. You need a smart and diligent individual. There's no question in that but it doesn't end there.

Going back to the op's tut/sample codes, those area where the data is being gathered and sent back to the database are jammed all over the place when it is even possible to separate it using different class or object to make it easier to read and troubleshoot.
I think you are barking at the wrong tree. You are speaking of service vs persistence layer. I am speaking of decoupling the frontend and the backend. You can still have your objects, classes, service, service, and persistence decoupling in the backend. In fact you must do that in the backend. On the frontend, you do the same. For example, if you are using React on the frontend, you don't tightly couple your presentational components with your state management.

It's like you are arguing who is the best actor and someone is arguing who is the best actress. But what I am arguing is the relationship between the actor and the actress.

Another scenario is when you need to update something from the area where the system does its user input calculations? In a tightly coupling, you will be needing to repack the entire solution just to implement the changes you've made only from those area.
Again you are barking at the wrong tree. You are the one who said it's better for systems to be tightly coupled. But it looks like you are changing your tune here?

Question, kung mas okay pala ang tightly coupling, paano mo implement yan sa isang malaking project? at paano kung group of dev kayo working on a 1 big project? when your components are tied and dependent together? paano ang disperse ng workload nyo?

I dont know much about the Representational State Transfer nor about SOAP.
Again it's you who said tightly coupled systems are better and offers better security. So I don't know why you are asking us that. We should be the one asking you.

REST and SOAP are totally different topics but again tightly coupled systems may make REST and SOAP difficult for your organization.
 

Trending Topics

Trending On This Forum

Unanswered Topics

Top