Php And MySQL - How To Order Html Table Data Using Php

Php & MySQL Database : How To Sort Html Table DataUsing Php


________________________________________________________


In this Php Tutorial we will see How To Use Sort Html Table Data In Ascending And Descending Order By Column Name Using MySQL Database And Php .

I Use In This Tutorial:
- NetBeans IDE .
- XAMPP .
- PhpMyAdmin .


 




Php Source Code:


<?php


// Ascending Order
if(isset($_POST['ASC']))
{
    $asc_query = "SELECT * FROM users ORDER BY age ASC";
    $result = executeQuery($asc_query);
}

// Descending Order
elseif (isset ($_POST['DESC'])) 
    {
          $desc_query = "SELECT * FROM users ORDER BY age DESC";
          $result = executeQuery($desc_query);
    }
    
    // Default Order
 else {
        $default_query = "SELECT * FROM users";
        $result = executeQuery($default_query);
}


function executeQuery($query)
{
    $connect = mysqli_connect("localhost", "root", "", "test_db");
    $result = mysqli_query($connect, $query);
    return $result;
}

?>

<!DOCTYPE html>
<html>
    <head>
        <title> PHP HTML TABLE ORDER DATA </title>
       <style>
            table,tr,th,td
            {
                border: 1px solid black;
            }
        </style>
    </head>
    <body>
     
        <form action="php_html_table_data_order.php" method="post">
         
            <input type="submit" name="ASC" value="Ascending"><br><br>
            <input type="submit" name="DESC" value="Descending"><br><br>
         
            <table>
                <tr>
                    <th>ID</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Age</th>
                </tr>
                <!-- populate table from mysql database -->
                <?php while ($row = mysqli_fetch_array($result)):?>
                <tr>
                    <td><?php echo $row[0];?></td>
                    <td><?php echo $row[1];?></td>
                    <td><?php echo $row[2];?></td>
                    <td><?php echo $row[3];?></td>
                </tr>
                <?php endwhile;?>
            </table>
        </form>
     
    </body>
</html>






///////////////OUTPUT: 




php table default order
Html Table Default Order
                                                             
php table ascending order
Html Table Ascending Order
                                                                   
php table descending order
Html Table Desending Order


                     

Java And MySQL - How To Order JTable Data Using Java

JAVA & MySQL Code - Ordering JTable Data In Java NetBeans

__________________________________________________________________________

In this java Tutorial we will learn How To Sort JTable Data Ascending And Descending By Column Name ('age' in this example) With  Java NetBeans And MySQL Database .
 .





Project Source Code:

// Create Class User

package JAVA_VIDEOS_TUTORIALS;

public class User {
    
    private int id;
    private String fname;
    private String lname;
    private int age;
    
    
    public User(int Id,String Fname,String Lname,int Age)
    {
        this.id = Id;
        this.fname = Fname;
        this.lname = Lname;
        this.age = Age;
    }
    
    public int getId()
    {
        return id;
    }
    
    public String getFname()
    {
        return fname;
    }
    
    public String getLname()
    {
        return lname;
    }
    
    public int getAge()
    {
        return age;
    }
}
      


// Creates new form Java_JTable_Order




package JAVA_VIDEOS_TUTORIALS;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;

public class Java_JTable_Order extends javax.swing.JFrame {

    /**
     * Creates new form Java_JTable_Order
     */
    public Java_JTable_Order() {
        initComponents();

        showUsersInJTable(query);

    }

    String query = "SELECT * FROM users";
    
    // function to get the connection
    public Connection getConnection()
    {
        Connection con = null;
        try
        {
          con = DriverManager.getConnection("jdbc:mysql://localhost/test_db","root",""); 
        }catch(Exception ex)
        {
            System.out.println(ex.getMessage());
        }
        return con;
    }
    
    // function return an arraylist of users
    public ArrayList<User> ListUsers(String query)
    {
        ArrayList<User> usersList = new ArrayList<User>();
        Connection con = getConnection();
        Statement st;
        ResultSet rs;
        try{
            st = con.createStatement();
            rs = st.executeQuery(query);
            User user;
            while(rs.next())
            {
                user = new User(
                              rs.getInt("id"),
                              rs.getString("fname"),
                              rs.getString("lname"),
                              rs.getInt("age")
                               );
                usersList.add(user);
            }
        }catch(Exception ex)
        {
            System.out.println(ex.getMessage());
        }
        
        return usersList;
        
    }
    
    
    // function to display the result in jtable
    public void showUsersInJTable(String OrderQuery)
    {
        ArrayList<User> users = ListUsers(OrderQuery);
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(new Object[]{"ID","First Name","Last Name","Age"});
        Object[] row = new Object[4];
        
        for(int i = 0; i < users.size(); i++)
        {
            row[0] = users.get(i).getId();
            row[1] = users.get(i).getFname();
            row[2] = users.get(i).getLname();
            row[3] = users.get(i).getAge();
            
            model.addRow(row);
        }
        
        jTable_Order.setModel(model);
    }
    
    
    
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton_ASC = new javax.swing.JButton();
        jButton_DESC = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable_Order = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton_ASC.setText("ASCENDING");
        jButton_ASC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_ASCActionPerformed(evt);
            }
        });

        jButton_DESC.setText("DESCENDING");
        jButton_DESC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DESCActionPerformed(evt);
            }
        });

        jTable_Order.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable_Order);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jButton_ASC)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton_DESC))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_ASC)
                    .addComponent(jButton_DESC))
                .addGap(27, 27, 27)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 459, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        
// button ascending
 private void jButton_ASCActionPerformed(java.awt.event.ActionEvent evt)
 {                                            
        // TODO add your handling code here:
        
        query = "SELECT * FROM users ORDER BY age ASC";
        showUsersInJTable(query);
    }                                           
// button descending
private void jButton_DESCActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: query = "SELECT * FROM users ORDER BY age DESC"; showUsersInJTable(query); } /** * @param args the command line arguments */ public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Java_JTable_Order.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Java_JTable_Order.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Java_JTable_Order.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Java_JTable_Order.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Java_JTable_Order().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton_ASC; private javax.swing.JButton jButton_DESC; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable_Order; // End of variables declaration }

// OUTPUT:
jtable default order
jtable default order


jtable ascending order
jtable ascending order
jtable descending order
jtable ascending order



Php Code : How To Show Images From A Folder

Php Code: How To Display Images From A Folder Using Php

________________________________________________________


In this Php Tutorial we will Learn How To Get And Display Only Images From A Directory Using Php .

I Use In This Tutorial:
- NetBeans IDE .
- XAMPP .



 




Php Source Code:

<?php

$dir_path = "folder/";
$extensions_array = array('jpg','png','jpeg');

if(is_dir($dir_path))
{
    $files = scandir($dir_path);
    
    for($i = 0; $i < count($files); $i++)
    {
        if($files[$i] !='.' && $files[$i] !='..')
        {
            // get file name
            echo "File Name -> $files[$i]<br>";
            
            // get file extension
            $file = pathinfo($files[$i]);
            $extension = $file['extension'];
            echo "File Extension-> $extension<br>";
            
           // check file extension
            if(in_array($extension, $extensions_array))
            {
            // show image
            echo "<img src='$dir_path$files[$i]' style='width:100px;height:100px;'><br>";
            }
        }
    }
}





                     
php show image




Php : How To Get Image Size From Directory Using Php

Php Code: How To Show Image Width And Height From A Folder Using Php

________________________________________________________


In this Php Tutorial we will Learn How  To Get And Display Images size ( width & height) From Folder Using Php .

I Use In This Tutorial:
- NetBeans IDE .
- XAMPP .



 




Php Source Code:

<?php

$dir_path = "images/";

if(is_dir($dir_path))
{
    $files = scandir($dir_path);
    
    for($i = 0; $i < count($files); $i++)
    {
        if($files[$i] != '.' && $files[$i] != '..')
        {
            echo "File Name -> $files[$i]<br>";
            
            $imageSize = getimagesize("$dir_path$files[$i]");
            
            echo " -Image Width : $imageSize[0]<br>";

            echo " -Image Height : $imageSize[1]<br>";

            //jpg or png or gif .........
            echo " -Image Type : $imageSize[2]<br>";

            echo " -Image Width And Height: $imageSize[3]<br>";

            // display the images
            echo"<img src='$dir_path$files[$i]' style='width:100px;height:100px;'><br><br>";
        }
    }
}





                     
php display images width and height



Php : How To Get File Extension From Directory Using Php

Php Code: How To Show Files Extension From A Folder Using Php

________________________________________________________


In this Php Tutorial we will Learn How  To Display Files Extensions From Folder Using Php .

I Use In This Tutorial:

- NetBeans IDE .
- XAMPP .



 




Php Source Code:

<?php

$dir_path = "folder/";

if(is_dir($dir_path))
{

    $files = scandir($dir_path);

    for($i = 0; $i < count($files); $i++)
    {

        if($files[$i] !='.' && $files[$i] != '..')
        {

            echo "File Name -> $files[$i]<br>";
            
            $file = pathinfo($files[$i]);

            $extension = $file['extension'];
           
            echo "File Extension -> $extension<br><br>";
        }
    }
}





                     
php files extensions


C# And MySQL - How To Search Data In MySQL And Display It On DataGridView Using C#

C# Code - How To Filter Data In MySQL And Show It On DataGridView Using C#

__________________________________________________________________________

In This C# Tutorial We Will Learn How To  Find Data In MySQL Database With A 
Specific  Value From TextBox And Display The Result In DataGridView Using CSharp
Programming Language .



Source Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace Csharp_And_MySQL
{
    public partial class Csharp_MySQL_Datagridview_Search : Form
    {
        MySqlConnection connection = new MySqlConnection("datasource = localhost;port = 3306; Initial Catalog = 'test_db'; username = root; password=");
        MySqlCommand command;
        MySqlDataAdapter adapter;
        DataTable table;

        public Csharp_MySQL_Datagridview_Search()
        {
            InitializeComponent();
        }

        private void Csharp_MySQL_Datagridview_Search_Load(object sender, EventArgs e)
        {
            searchData("");
        }

        public void searchData(string valueToSearch)
        {
            string query = "SELECT * FROM users WHERE CONCAT(`id`, `fname`, `lname`, `age`) like '%"+valueToSearch+"%'";
            command = new MySqlCommand(query, connection);
            adapter = new MySqlDataAdapter(command);
            table = new DataTable();
            adapter.Fill(table);
            dataGridView1.DataSource = table;
        }

        private void BTN_SEARCH_Click(object sender, EventArgs e)
        {
            string valueToSearch = textBoxValueToSearch.Text.ToString();
            searchData(valueToSearch);
        }

    }
}


=> OUTPUT:

c# datagridview filter

JAVA And MySQL - How To Search Data In MySQL Database And Display It In JTable Using Java

JAVA Code - How To Filter Data From MySQL Database And Show It In JTable Using Java NetBeans

__________________________________________________________________________

In this java Tutorial we will learn How To Find Data In MySQL Database With A Specific 
Value From JTextField And Display The Result In JTable In Java NetBeans .


java jtable mysql find


                                                                  Part 1



Part 2


Project Source Code:

// Create Class User


package JAVA_VIDEOS_TUTORIALS;

public class User {
    
    private int id;
    private String fname;
    private String lname;
    private int age;
    
    
    public User(int Id,String Fname,String Lname,int Age)
    {
        this.id = Id;
        this.fname = Fname;
        this.lname = Lname;
        this.age = Age;
    }
    
    public int getId()
    {
        return id;
    }
    
    public String getFname()
    {
        return fname;
    }
    
    public String getLname()
    {
        return lname;
    }
    
    public int getAge()
    {
        return age;
    }
}
      

// Creates new form JTable_Search


package JAVA_VIDEOS_TUTORIALS;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author 1BestCsharp
 */
public class JTable_Search extends javax.swing.JFrame {

    /**
     * Creates new form JTable_Search
     */
    public JTable_Search() {
        initComponents();
        
        // call findUsers function
        findUsers();
        
    }

    
    // function to connect to mysql database
    public Connection getConnection()
    {
        Connection con = null;
        
        try{
            con = DriverManager.getConnection("jdbc:mysql://localhost/test_db","root","");
        }catch(Exception ex){
            System.out.println(ex.getMessage());
        }
        
        return con;
    }
    
 // function to return users arraylist with particular data 
    public ArrayList<User> ListUsers(String ValToSearch)
    {
        ArrayList<User> usersList = new ArrayList<User>();
        
        Statement st;
        ResultSet rs;
        
        try{
            Connection con = getConnection();
            st = con.createStatement();
            String searchQuery = "SELECT * FROM `users` WHERE CONCAT(`id`, `fname`, `lname`, `age`) LIKE '%"+ValToSearch+"%'";
            rs = st.executeQuery(searchQuery);
            
            User user;
            
            while(rs.next())
            {
                user = new User(
                                 rs.getInt("id"),
                                 rs.getString("fname"),
                                 rs.getString("lname"),
                                 rs.getInt("age")
                                );
                usersList.add(user);
            }
            
        }catch(Exception ex){
            System.out.println(ex.getMessage());
        }
        
        return usersList;
    }
    
    // function to display data in jtable
    public void findUsers()
    {
        ArrayList<User> users = ListUsers(jText_Search.getText());
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(new Object[]{"ID","Fname","Lname","Age"});
        Object[] row = new Object[4];
        
        for(int i = 0; i < users.size(); i++)
        {
            row[0] = users.get(i).getId();
            row[1] = users.get(i).getFname();
            row[2] = users.get(i).getLname();
            row[3] = users.get(i).getAge();
            model.addRow(row);
        }
       jTable_Users.setModel(model);
       
    }
    
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jButton_Search = new javax.swing.JButton();
        jText_Search = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable_Users = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton_Search.setText("Search");
        jButton_Search.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_SearchActionPerformed(evt);
            }
        });

        jText_Search.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N

        jTable_Users.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jTable_Users.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable_Users);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(22, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jText_Search, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Search)
                        .addGap(136, 136, 136))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 500, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(29, 29, 29))))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Search)
                    .addComponent(jText_Search, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(41, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>  
                        

    // Button Filter/search 
     
    private void jButton_SearchActionPerformed(java.awt.event.ActionEvent evt) {                                               
     
       findUsers();
       
    }                                              

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JTable_Search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JTable_Search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JTable_Search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JTable_Search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JTable_Search().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton_Search;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable_Users;
    private javax.swing.JTextField jText_Search;
    // End of variables declaration                   
}

// OUTPUT:
java jtable filter
Java JTable Data From Mysql Search