Database Data Navigation in PHP

How to Navigate and Display Database Records Using PHP

How to Navigate and Display Database Records Using PHP


In this PHP tutorial, we will see how to to retrieve product information from a database and display it within an HTML form. 
Users can navigate through the products by using navigation buttons, and the form fields will dynamically update to show the details of the selected product.



Project Source Code:



<?php

// Connect to the database
require_once "db_connect.php";

// Define the SQL query to select all products from the "product" table
$query = "SELECT * FROM `product`";

// Prepare the SQL statement
$stmt = $conn -> prepare($query);

// Execute the SQL statement
$stmt->execute();

// Fetch all the results from the statement and store them in an array
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Initialize an empty array to store the products
$products = array();

foreach( $results as $row ){
$product = array("id"=>$row["id"],
"name"=>$row["name"],
"price"=>$row["price"],
"image"=>$row["image"]
);

// Add the product array to the products array
array_push($products, $product);
}


?>

<!DOCTYPE html>
<html>
<head>
<title>Data Navigation</title>
<style>

body{ font-family:Arial, sans-serif; background-color:#f2f2f2; }

form{ background-color:#fff; padding:20px; width:500px; margin: 25px auto;
border-radius:5px; box-shadow: 0 0 10px rgba(0,0,0,0.2); }
h1{ text-align:center; color:#333; margin-bottom:20px; }

.form-row{ margin:10px 0; }

input{ padding:10px; margin:10px 0; border:1px solid #ccc;
border-radius:4px; box-sizing:border-box; width:100%; }

button{ background-color:#4caf50; color:#fff; padding:10px 20px; border:none;
border-radius:4px; cursor:pointer; margin-top:10px; width:24%;
font-size:16px; }

button:hover{ background-color:#45a049; }

#image{ display:flex; align-items:flex-start; }

#image label{ margin-right:10px; }

#image img{ margin:10px; width:50%; height:150px; border-radius:5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.3); }

</style>
</head>
<body>

<form id="product-form">
<h1>Product Information</h1>
<div class="form-row">
<label for="product-id">ID:</label>
<input type="text" id="product-id" name="product-id">
</div>
<div class="form-row">
<label for="product-name">Name:</label>
<input type="text" id="product-name" name="product-name">
</div>
<div class="form-row">
<label for="product-price">Price:</label>
<input type="text" id="product-price" name="product-price">
</div>
<div class="form-row">
<div id="image">
<label for="product-image">Image:</label>
<img id="product-image" src="">
</div>
</div>
<div class="form-row">
<button type="button" id="btn-first">First</button>
<button type="button" id="btn-prev">Previous</button>
<button type="button" id="btn-next">Next</button>
<button type="button" id="btn-last">Last</button>
</div>

<script>

// convert the PHP array to a JavaScript object in JSON format.
const products = <?php echo json_encode($products); ?>

// Get the buttons
const btnFirst = document.getElementById('btn-first');
const btnNext = document.getElementById('btn-next');
const btnPrevious = document.getElementById('btn-prev');
const btnLast = document.getElementById('btn-last');

// Define a variable to keep track of the current index
let currentIndex = 0;

// Function to update the form fields based on the current index
function updateForm(){

const product = products[currentIndex];

document.getElementById('product-id').value = product.id;
document.getElementById('product-name').value = product.name;
document.getElementById('product-price').value = product.price;
document.getElementById('product-image').src = product.image;

}

// Function to handle button clicks
function handleButtonClick(e)
{
switch(e.target.id){
case 'btn-first':
currentIndex = 0;
break;
case 'btn-prev':
currentIndex = Math.max( currentIndex - 1, 0 );
break;
case 'btn-next':
currentIndex = Math.min( currentIndex + 1, products.length - 1 );
break;
case 'btn-last':
currentIndex = products.length - 1;
break;
default:
break;
}

updateForm();

}

// Add event listeners to the buttons
btnFirst.addEventListener('click', handleButtonClick);
btnNext.addEventListener('click', handleButtonClick);
btnPrevious.addEventListener('click', handleButtonClick);
btnLast.addEventListener('click', handleButtonClick);

// Initialize the form
updateForm();


</script>


</body>
</html>



Code Explanation:

PHP Section: This PHP code connects to a database using "db_connect.php," defines and executes an SQL query to select all products from a "product" table, fetches and stores the results in an array, and constructs an array of product information.

HTML/JavaScript Section: This code generates an HTML form with fields for product information.
It includes navigation buttons (First, Previous, Next, Last) to move between products and applies CSS styles.
JavaScript manages button clicks, updates form fields with product data, and keeps track of the current product.
listeners are added for button interaction, and the form is initialized through the updateForm function.



OUTPUT:


Database Data Navigation in PHP

Data Navigation in PHP




if you want the source code click on the download button below










Java Combobox With JTextArea

How to Add TextArea to a Combobox In Java Netbeans

Java Combobox With JTextArea


In this Java Tutorial we will see How To Create a JCombobox With JTextArea Inside It In Java Using Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:


package new_tutorials;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListCellRenderer;

/**
 *
 * @author 1BestCsharp
 */
public class TextAreaComboboxFrame extends JFrame{
    
    private JComboBox<TextAreaComboboxElement> comboBox;
    private JTextArea displayTextArea;
    
    public TextAreaComboboxFrame(){
        // Set up the JFrame
        setTitle("TextArea Combobox");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Set the layout manager for the JFrame
        setLayout(new FlowLayout());
        // Create a JComboBox and set its renderer
        comboBox = new JComboBox<>();
        comboBox.setRenderer(new TextAreaComboboxRenderer());
        
        // Add three items with multiline text to the combobox
        comboBox.addItem(new TextAreaComboboxElement("Item 1", "This is the first item.\nIt has multiple lines."));
        comboBox.addItem(new TextAreaComboboxElement("Item 2", "This is the second item.\nIt also has multiple lines."));
        comboBox.addItem(new TextAreaComboboxElement("Item 3", "This is the third item.\nIt's multiline as well."));
        
        // Add an item listener to handle item selection
        comboBox.addItemListener((e) -> {
           
            TextAreaComboboxElement selectedItem = (TextAreaComboboxElement)comboBox.getSelectedItem();
            
            if(selectedItem != null){
                displayTextArea.setText(selectedItem.getText());
            }
            
        });
        
        add(comboBox);
        displayTextArea = new JTextArea(5,20);
        displayTextArea.setEditable(false);
        add(new JScrollPane(displayTextArea));
        setSize(400,400);
        setLocationRelativeTo(null);
        
        // Set the initial text in the display area
        TextAreaComboboxElement initialItem = comboBox.getItemAt(0);
        displayTextArea.setText(initialItem.getText());
        
    }
    
    
    
    
    
    // Create an Inner class representing elements in the combobox
    public static class TextAreaComboboxElement{
        private final String label;
        private final String text;
        
        // constructor
        public TextAreaComboboxElement(String label, String text){
            this.label = label;
            this.text = text;
        }
        
        // Getters
        public String getLabel(){ return label; }
        
        public String getText(){ return text; }
        
    }
    
    
    // Create an Inner class representing the renderer for the combobox
    private class TextAreaComboboxRenderer extends JPanel implements ListCellRenderer<TextAreaComboboxElement>{

        private final JLabel label;
        private final JTextArea textArea;
        
        public TextAreaComboboxRenderer(){
            setLayout(new BorderLayout());
            label = new JLabel();
            add(label, BorderLayout.NORTH);
            textArea = new JTextArea();
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            textArea.setEditable(false);
            add(textArea, BorderLayout.CENTER);
        }
        
        // Implement the rendering of combobox elements
        @Override
        public Component getListCellRendererComponent(JList<? extends TextAreaComboboxElement> list, TextAreaComboboxElement value, int index, boolean isSelected, boolean cellHasFocus) {
            // Set the label and text of the renderer components
            label.setText(value.getLabel());
            textArea.setText(value.getText());
            // Set the background and foreground based on selection
            if(isSelected){
                setBackground(Color.BLACK);
                getComponent(0).setForeground(Color.YELLOW);
            }
            else
            {
                setBackground(list.getBackground());
                getComponent(0).setForeground(list.getForeground());
                //setForeground(list.getForeground());
            }
            
            return this;
            
        }
        
    }
    
    
    
    public static void main(String[] args) {
        TextAreaComboboxFrame frame = new TextAreaComboboxFrame();
        frame.setVisible(true);
    }

}


The Final Result:


How to Add TextArea to a Combobox In Java Netbeans


How to Add JTextArea to a JCombobox In Java Netbeans








Java JList With JTextArea

How to Add TextArea to a JList In Java Netbeans

How to Add TextArea to a JList In Java Netbeans


In this Java Tutorial we will see How To Create a JList With JTextArea Inside It In Java Using Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:



package new_tutorials;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListCellRenderer;

/**
 *
 * @author 1BestCsharp
 */
public class TextAreaInJListFrame extends JFrame{

    private JList<TextAreaListElement> textAreaList;
    
    public TextAreaInJListFrame(){
        setTitle("TextArea In JList");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        
        List<TextAreaListElement> elements = new ArrayList<>();
        elements.add(new TextAreaListElement("Item 1", "Description for Item Line Description for Item 1 Line 2 Description for Item 1 Line 3"));
        elements.add(new TextAreaListElement("Item 2", "Description Description DescriptionDescription DescriptionDescription Description Description Description Description for Item 2"));
        elements.add(new TextAreaListElement("Item 3", "Description for Item 3"));
        elements.add(new TextAreaListElement("Item 11", "Description for Item Line Description for Item 1 Line 2 Description for Item 1 Line 3"));
        elements.add(new TextAreaListElement("Item 22", "Description Description DescriptionDescription DescriptionDescription Description Description Description Description for Item 2"));
        elements.add(new TextAreaListElement("Item 33", "Description for Item 3"));
        elements.add(new TextAreaListElement("Item 41", "Description for Item Line Description for Item 1 Line 2 Description for Item 1 Line 3"));
        elements.add(new TextAreaListElement("Item 52", "Description Description DescriptionDescription DescriptionDescription Description Description Description Description for Item 2"));
        elements.add(new TextAreaListElement("Item 63", "Description for Item 3"));
        elements.add(new TextAreaListElement("Item 71", "Description for Item Line Description for Item 1 Line 2 Description for Item 1 Line 3"));
        elements.add(new TextAreaListElement("Item 82", "Description Description DescriptionDescription DescriptionDescription Description Description Description Description for Item 2"));
        elements.add(new TextAreaListElement("Item 93", "Description for Item 3"));
        elements.add(new TextAreaListElement("Item 211", "Description for Item Line Description for Item 1 Line 2 Description for Item 1 Line 3"));
        elements.add(new TextAreaListElement("Item 992", "Description Description DescriptionDescription DescriptionDescription Description Description Description Description for Item 2"));
        elements.add(new TextAreaListElement("Item 543", "Description for Item 3"));

        textAreaList = new JList<>(elements.toArray(TextAreaListElement[] :: new));
        textAreaList.setCellRenderer(new TextAreListRenderer());
        
        JScrollPane scrollPane = new JScrollPane(textAreaList);
        add(scrollPane, BorderLayout.CENTER);
        setSize(400,300);
        setLocationRelativeTo(null);
        
    }
    
    
    public static class TextAreaListElement{
        private final String label;
        private final String description;
        
        public TextAreaListElement(String label, String description){
            this.label = label;
            this.description = description;
        }
        
        public String getLabel(){
            return label;
        }
        
        public String getDescription(){
            return description;
        }
        
    }
    
    
    // create a renderer to display the textArea
    private class TextAreListRenderer extends JTextArea implements ListCellRenderer<TextAreaListElement>{

        public TextAreListRenderer(){
            setLineWrap(true);
            setWrapStyleWord(true);
            setMargin(new Insets(5, 10, 5, 10));
            setFont(new Font("Arial", Font.PLAIN, 16));
            setPreferredSize(new Dimension(300,80));
        }
        
        @Override
        public Component getListCellRendererComponent(JList<? extends TextAreaListElement> list, TextAreaListElement value, int index, boolean isSelected, boolean cellHasFocus) {
         
            setEnabled(list.isEnabled());
            setText(value.getLabel()+ "\n" + value.getDescription());
            
            if(isSelected){
                setBackground(Color.BLACK);
                setForeground(Color.YELLOW);
            }
            else{
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            
            return this;
        }
        
    }
    
    
    public static void main(String[] args) {
        
        TextAreaInJListFrame frame = new TextAreaInJListFrame();
        frame.setVisible(true);
        
    }
}


The Final Result:


Java JList With JTextArea

JList With JTextArea In Java