Sunday, 4 June 2023

PHP Project on Parking Management System - How to Source Code Download & Run



Introduction:


Parking management systems have become an integral part of urban infrastructure, providing efficient parking solutions and improving the overall traffic flow. In this blog post, we will explore a PHP project on a parking management system and guide you on how to download and run it on your local machine. Whether you are a student looking for a project or a developer interested in understanding the implementation of such systems, this article is for you. So, let's get started!


PHP Project on Parking Management System - How to Source Code Download & Run


Step 1: Downloading the Project


To begin with, you need to download the parking management system project files. So below You can find download link for PHP Parking Management System Project source code file. Once you find a project that suits your requirements, then you can download the project as a ZIP file to your local machine.



Step 2: Setting Up the Environment


Before running the project, make sure you have the necessary environment set up. You will need a web server software (such as Apache or Nginx) and a database server (such as MySQL) installed on your machine. Additionally, ensure you have PHP installed and configured properly. Refer to the documentation for each of these components to install them correctly according to your operating system.

Step 3: Extracting the Project Files


Once you have downloaded the project and set up the required environment, extract the ZIP file you downloaded earlier. You should now have a directory containing all the project files. Make sure to remember the location where you extracted the files, as you will need it in the next step.





Step 4: Database Setup


Parking management systems require a database to store information such as parking slots, vehicle details, and user data. Before running the project, create a database using the database server you installed earlier. The project files should include a database dump file (usually in SQL format) with name like database.sql. So in your database you have to create one database with name like parking. Remember to configure the database connection settings in the project files with file name like config.php according to your database setup.

Step 5: Running the Project


Now that everything is set up, it's time to run the project. Start your web server and make sure it is configured to serve PHP files correctly. Copy the extracted project files to the web server's document root directory. Open your web browser and enter the URL corresponding to the location where you copied the project files. The exact URL will depend on your web server configuration, but it will typically be something like http://localhost/parking-management-system/.

Feature of Parking Management System


Admin Side


  1. Admin can Add Edit View and Remove Parking Category Data
  2. Admin can Add Edit View and Remove Parking Duration Data
  3. Admin can Add Edit View and Remove Parking Rate Data
  4. Admin can Add Edit View and Remove Parking Slot Data
  5. Admin can view which Slot is Available or not Available for Vehicle Parking
  6. Admin can Add Edit View and Remove Vehicle Parking Data
  7. Admin can export Vehicle Parking Data in CSV file according different date filter
  8. Admin can view Analytics data like Total Revenue and Total Vehicle Park Data in Graphical Format with Date Filter
  9. Admin can Add Edit and Remove Sub User Data, so this is multi user Parking System
  10. Admin can Edit Profile detail like Email Address and Password Data
  11. Admin can Set Parking Master Data also


Sub User Side


  1. Sub User can edit their profile data like email and password detail
  2. Sub User can Add Edit View and Delete Vehicle Parking Data

Conclusion:


In this blog post, we explored a PHP project on a parking management system and provided a step-by-step guide on how to download and run it on your local machine. By following these steps, you can gain insights into the implementation of parking management systems and customize them according to your requirements. Remember, this project serves as a starting point, and you can enhance it further by adding additional features and improving the user interface. Happy coding!



Thursday, 6 April 2023

Live Table Insert Update Delete in Node.js with MySQL

Live Table Insert Update Delete in Node.js with MySQL

Live Table Add Edit Delete MySQL Data in Node.js" is a popular feature of web applications that allows users to manipulate data on a page without having to refresh the page. This feature can be implemented using Node.js and MySQL, and in this article, we will walk through a step-by-step guide on how to create a live table that can add, edit and delete data using Node.js and MySQL.

To get started, we need to create a Node.js project and install the required dependencies. We can do this by running the following commands:


mkdir live_table_insert_update_delete
cd live_table_insert_update_delete
npm init -y
npm install express mysql body-parser


The above commands will create a new directory called live_table_insert_update_delete, initialize a new Node.js project and install the required dependencies.

Next, we need to create a MySQL database and table that we will use to store our sample data. We can do this by running the following SQL commands:


CREATE DATABASE testing;

USE testing;

CREATE TABLE sample_data (
  id int(11) NOT NULL AUTO_INCREMENT,
  first_name varchar(255) NOT NULL,
  last_name varchar(255) NOT NULL,
  age int(11) NOT NULL,
  PRIMARY KEY (id)
);


The above commands will create a new database called testing and a table called sample_data with four columns: id, first_name, last_name, and age.

Now we have create a new file called server.js and add the following code:

server.js

//imports the Express framework
const express = require('express');

//import mysql module
const mysql = require('mysql');

//import body-parser module
const bodyParser = require('body-parser');

//creates an instance of the Express application
const app = express();

// Add middleware for parse incoming request body
app.use(bodyParser.urlencoded({ extended : false }));

// Add middleware for parse incoming data in JSON
app.use(bodyParser.json());

//Make MySQL Database Connection
const connection = mysql.createConnection({
	host : 'localhost',
	database : 'testing',
	user : 'root',
	password : ''
});

//Check MySQL Database Connection
connection.connect((error) => {
	console.log('MySQL Database is connected Successfully');
});

//Create Route for Load index.html file
app.get("/", (request, response) => {
	response.sendFile(__dirname + "/index.html");
});

//Crate Route handle get request
app.get("/get_data", (request, response) => {
	const sql = `SELECT * FROM sample_data ORDER BY id ASC`;

	connection.query(sql, (error, results) => {
		console.log(error);
		response.send(results);

	});
});

//Create Route for Insert Data Operation
app.post("/add_data", (request, response) => {

	const first_name = request.body.first_name;

	const last_name = request.body.last_name;

	const age = request.body.age;

	const sql = `
	INSERT INTO sample_data 
	(first_name, last_name, age) 
	VALUES ("${first_name}", "${last_name}", "${age}")
	`;

	connection.query(sql, (error, results) => {
		response.json({
			message : 'Data Added'
		});
	});

});

//Create Route for Update Data Operation
app.post('/update_data', (request, response) => {

	const variable_name = request.body.variable_name;

	const variable_value = request.body.variable_value;

	const id = request.body.id;

	const sql = `UPDATE sample_data SET `+variable_name+`= "${variable_value}" WHERE id = "${id}"`;

	connection.query(sql, (error, results) => {

		response.json({
			message : 'Data Updated'
		});

	});

});

//Create Route for Delete data operation
app.post("/delete_data", (request, response) => {

	const id = request.body.id;

	const sql = `DELETE FROM sample_data WHERE id = '${id}'`;

	connection.query(sql, (error, results) => {
		response.json({
			message : 'Data Deleted'
		});
	});

});

app.listen(3000, () => {
	console.log('Server listening on port 3000');
});


This is a Node.js server-side code that creates a web application using the Express framework, and connects to a MySQL database to perform CRUD (Create, Read, Update, and Delete) operations. Here is a brief description of the code:

  1. Import the required modules: Express, MySQL, and body-parser.
  2. Create an instance of the Express application.
  3. Add middleware for parsing incoming request body, including JSON data.
  4. Create a MySQL database connection and check if it is connected successfully.
  5. Create a route to serve the index.html file.
  6. Create a route to handle GET requests and retrieve data from the MySQL database.
  7. Create a route to handle POST requests and insert data into the MySQL database.
  8. Create a route to handle POST requests and update data in the MySQL database.
  9. Create a route to handle POST requests and delete data in the MySQL database.
  10. Listen to the server on port 3000.

Overall, this code provides the backend functionality to serve a web application and perform CRUD operations on a MySQL database.





After this, we have to create index.html file for write HTML code and Vanilla JavaScript code.

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Live Table Insert Update Delete in Node.js with MySQL</title>
    <link href="https://getbootstrap.com/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5 mb-5">
        <h1 class="text-danger text-center"><b>Inline Table CRUD Operation in Node.js with MySQL - Delete Data</b></h1>
        <div class="mt-3 mb-3">
            <div class="card">
                <div class="card-header">Sample Data</div>
                <div class="card-body">
                    <table class="table table-bordered mt-3">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Age</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="results">

                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

<script>

    const results_body = document.querySelector('#results');

    load_data();

    function load_data()
    {
        const request = new XMLHttpRequest();

        request.open(`get`, `/get_data`);

        let html = '';

        request.onreadystatechange = () => {
            if(request.readyState === XMLHttpRequest.DONE && request.status === 200)
            {
                const results = JSON.parse(request.responseText);

                results.forEach(result => {
                    html += `
                    <tr>
                        <td>`+result.id+`</td>
                        <td contenteditable onblur="update_data(this, 'first_name', '`+result.id+`')">`+result.first_name+`</td>
                        <td contenteditable onblur="update_data(this, 'last_name', '`+result.id+`')">`+result.last_name+`</td>
                        <td contenteditable onblur="update_data(this, 'age', '`+result.id+`')">`+result.age+`</td>
                        <td><button type="button" class="btn btn-danger btn-sm" onclick="delete_data(`+result.id+`)">Remove</button></td>
                    </tr>
                    `;
                });

                html += `
                <tr>
                    <td></td>
                    <td contenteditable id="first_name_data"></td>
                    <td contenteditable id="last_name_data"></td>
                    <td contenteditable id="age_data"></td>
                    <td><button type="button" class="btn btn-success btn-sm" onclick="add_data()">Add</button></td>
                </tr>
                `;

                results_body.innerHTML = html;
            }
        };

        request.send();
    }

    function add_data()
    {
        const first_name = document.getElementById('first_name_data');

        const last_name = document.getElementById('last_name_data');

        const age = document.getElementById('age_data');

        const param = `first_name=`+first_name.innerText+`&last_name=`+last_name.innerText+`&age=`+age.innerText+``;

        const request = new XMLHttpRequest();

        request.open(`POST`, `/add_data`, true);

        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        request.onreadystatechange = () => {

            if(request.readyState === XMLHttpRequest.DONE && request.status === 200)
            {
                alert("Data Added");

                load_data();
            }

        };

        request.send(param);
    }

    function update_data(element, variable_name, id)
    {
        const param = `variable_name=`+variable_name+`&variable_value=`+element.innerText+`&id=`+id+``;

        const request = new XMLHttpRequest();

        request.open(`POST`, `/update_data`, true);

        //Send the proper header information along with the request
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        request.onreadystatechange = () => {

            if(request.readyState === XMLHttpRequest.DONE && request.status === 200)
            {

                alert('Data Updated');

            }

        };

        request.send(param);
    }

    function delete_data(id)
    {
        if(confirm("Are you sure you want to remove it?"))
        {
            const param = `id=`+id+``;

            const request = new XMLHttpRequest();

            request.open('POST', `/delete_data`, true);

            request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

            request.onreadystatechange = () => {

                if(request.readyState === XMLHttpRequest.DONE && request.status === 200)
                {
                    alert('Data Deleted');

                    load_data();
                }

            };

            request.send(param);
        }
    }

</script>


This code is a web page with a table that performs CRUD (Create, Read, Update, Delete) operations in Node.js with MySQL. The table is displayed in a Bootstrap card, and it shows a list of people with their IDs, first and last names, email, and gender. The table can be edited inline, and it has an "Add" button that adds a new row to the table, a "Remove" button that deletes a row from the table, and an "Update" button that updates the data in the table.

The JavaScript code uses XMLHttpRequest to send asynchronous HTTP requests to the server-side Node.js application, which interacts with a MySQL database to perform the CRUD operations. The load_data() function sends a GET request to the server-side application to retrieve the data and displays it in the table using HTML. The add_data(), update_data() and delete_data() functions send POST requests to the server-side application to perform the corresponding operations.

In conclusion, the Live Table Add Edit Delete MySQL Data in Node.js is a web application that allows users to perform basic CRUD (Create, Read, Update, and Delete) operations on a MySQL database using Node.js. The application uses an HTML table to display the data from the database, which can be edited, updated, and deleted in real-time. The code uses AJAX requests to communicate with the server-side Node.js application, which handles the database operations. This application can be useful for developers who want to learn how to build a basic CRUD application using Node.js and MySQL or for those who need a simple way to manage data stored in a MySQL database.

Thursday, 30 March 2023

How to Make Shopping Cart in Node.js Express & MySQL


Introduction


In this tutorial, we will learn how to create a simple shopping cart in Node.js with session storage. We will create a simple e-commerce application that will allow users to add items to their cart and view their cart. The shopping cart will be implemented using session storage to store the cart data.

Prerequisites:


  • Node.js installed on your machine.
  • Basic knowledge of Node.js and Express.js.

How to Make Shopping Cart in Node.js Express & MySQL

Step 1: Set up the project and install dependencies


Create a new directory for your project and navigate to that directory using the command prompt. Once you are inside the directory, initialize the Node.js project by running the following command:


npm init


This will create a package.json file in your project directory. Next, we need to install the required dependencies for our project. We will be using the following dependencies:

  • Express.js: A Node.js web application framework.
  • body-parser: A Node.js middleware for handling HTTP request body parsing.
  • express-session: A Node.js middleware for handling user sessions.
  • mysql: A Node.js driver for MySQL database.

Install the dependencies using the following command:


npm install express body-parser express-session mysql


Step 2: Create the product table


Create a new table named product in your MySQL database using the following SQL script:


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `product_id` int(20) NOT NULL,
  `product_name` varchar(120) NOT NULL,
  `product_brand` varchar(100) NOT NULL,
  `product_price` decimal(8,2) NOT NULL,
  `product_ram` char(5) NOT NULL,
  `product_storage` varchar(50) NOT NULL,
  `product_camera` varchar(20) NOT NULL,
  `product_image` varchar(100) NOT NULL,
  `product_quantity` mediumint(5) NOT NULL,
  `product_status` enum('0','1') NOT NULL COMMENT '0-active,1-inactive'
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Indexes for table `product`
--
ALTER TABLE `product`
  ADD PRIMARY KEY (`product_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
  MODIFY `product_id` int(20) NOT NULL AUTO_INCREMENT;


Insert some sample data into the product table using the following SQL script:


--
-- Dumping data for table `product`
--

INSERT INTO `product` (`product_id`, `product_name`, `product_brand`, `product_price`, `product_ram`, `product_storage`, `product_camera`, `product_image`, `product_quantity`, `product_status`) VALUES
(1, 'Honor 9 Lite (Sapphire Blue, 64 GB)  (4 GB RAM)', 'Honor', '14499.00', '4', '64', '13', 'image-1.jpeg', 10, '1'),
(2, '\r\nInfinix Hot S3 (Sandstone Black, 32 GB)  (3 GB RAM)', 'Infinix', '8999.00', '3', '32', '13', 'image-2.jpeg', 10, '1'),
(3, 'VIVO V9 Youth (Gold, 32 GB)  (4 GB RAM)', 'VIVO', '16990.00', '4', '32', '16', 'image-3.jpeg', 10, '1'),
(4, 'Moto E4 Plus (Fine Gold, 32 GB)  (3 GB RAM)', 'Moto', '11499.00', '3', '32', '8', 'image-4.jpeg', 10, '1'),
(5, 'Lenovo K8 Plus (Venom Black, 32 GB)  (3 GB RAM)', 'Lenevo', '9999.00', '3', '32', '13', 'image-5.jpg', 10, '1'),
(6, 'Samsung Galaxy On Nxt (Gold, 16 GB)  (3 GB RAM)', 'Samsung', '10990.00', '3', '16', '13', 'image-6.jpeg', 10, '1'),
(7, 'Moto C Plus (Pearl White, 16 GB)  (2 GB RAM)', 'Moto', '7799.00', '2', '16', '8', 'image-7.jpeg', 10, '1'),
(8, 'Panasonic P77 (White, 16 GB)  (1 GB RAM)', 'Panasonic', '5999.00', '1', '16', '8', 'image-8.jpeg', 10, '1'),
(9, 'OPPO F5 (Black, 64 GB)  (6 GB RAM)', 'OPPO', '19990.00', '6', '64', '16', 'image-9.jpeg', 10, '1'),
(10, 'Honor 7A (Gold, 32 GB)  (3 GB RAM)', 'Honor', '8999.00', '3', '32', '13', 'image-10.jpeg', 10, '1'),
(11, 'Asus ZenFone 5Z (Midnight Blue, 64 GB)  (6 GB RAM)', 'Asus', '29999.00', '6', '128', '12', 'image-12.jpeg', 10, '1'),
(12, 'Redmi 5A (Gold, 32 GB)  (3 GB RAM)', 'MI', '5999.00', '3', '32', '13', 'image-12.jpeg', 10, '1'),
(13, 'Intex Indie 5 (Black, 16 GB)  (2 GB RAM)', 'Intex', '4999.00', '2', '16', '8', 'image-13.jpeg', 10, '1'),
(14, 'Google Pixel 2 XL (18:9 Display, 64 GB) White', 'Google', '61990.00', '4', '64', '12', 'image-14.jpeg', 10, '1'),
(15, 'Samsung Galaxy A9', 'Samsung', '36000.00', '8', '128', '24', 'image-15.jpeg', 10, '1'),
(16, 'Lenovo A5', 'Lenovo', '5999.00', '2', '16', '13', 'image-16.jpeg', 10, '1'),
(17, 'Asus Zenfone Lite L1', 'Asus', '5999.00', '2', '16', '13', 'image-17.jpeg', 10, '1'),
(18, 'Lenovo K9', 'Lenovo', '8999.00', '3', '32', '13', 'image-18.jpeg', 10, '1'),
(19, 'Infinix Hot S3x', 'Infinix', '9999.00', '3', '32', '13', 'image-19.jpeg', 10, '1'),
(20, 'Realme 2', 'Realme', '8990.00', '4', '64', '13', 'image-20.jpeg', 10, '1'),
(21, 'Redmi Note 6 Pro', 'Redmi', '13999.00', '4', '64', '20', 'image-21.jpeg', 10, '1'),
(22, 'Realme C1', 'Realme', '7999.00', '2', '16', '15', 'image-22.jpeg', 10, '1'),
(23, 'Vivo V11', 'Vivo', '22900.00', '6', '64', '21', 'image-23.jpeg', 10, '1'),
(24, 'Oppo F9 Pro', 'Oppo', '23990.00', '6', '64', '18', 'image-24.jpg', 10, '1'),
(25, 'Honor 9N', 'Honor', '11999.00', '4', '64', '15', 'image-25.jpg', 10, '1'),
(26, 'Redmi 6A', 'Redmi', '6599.00', '2', '16', '13', 'image-26.jpeg', 10, '1'),
(27, 'InFocus Vision 3', 'InFocus', '7399.00', '2', '16', '13', 'image-27.jpeg', 10, '1'),
(28, 'Vivo Y69', 'Vivo', '11390.00', '3', '32', '16', 'image-28.jpeg', 10, '1'),
(29, 'Honor 7x', 'Honor', '12721.00', '4', '32', '18', 'image-29.jpeg', 10, '1'),
(30, 'Nokia 2.1', 'Nokia', '6580.00', '2', '1', '8', 'image-30.jpeg', 10, '1');





Step 3: Create the server.js file


Create a new file named server.js in your project directory and add the following code:

server.js

const express = require('express');

const mysql = require('mysql');

const body_parser = require('body-parser');

const session = require('express-session');

const app = express();

app.use(body_parser.urlencoded({ extended : false }));

app.use(body_parser.json());

//middleware for serving static file
app.use(express.static('public'));

//Set up EJS as template engine
app.set('view engine', 'ejs');

//Make MySQL Database Connection
const connection = mysql.createConnection({
	host : 'localhost',
	database : 'testing',
	user : 'root',
	password : ''
});

//Check MySQL Database Connection
connection.connect((error) => {
	console.log('MySQL Database is connected Successfully');
});

//Set up Session Middleware
app.use(session({
	secret : '1234567890abcdefghijklmnopqrstuvwxyz',
	resave : false,
	saveUninitialized : true,
	cookie : { secure : false }
}));

//Create Route for Load Product Data
app.get("/", (request, response) => {

	const query = `SELECT * FROM product LIMIT 3`;

	//Execute Query
	connection.query(query, (error, result) => {

		if(!request.session.cart)
		{
			request.session.cart = [];
		}

		response.render('product', { products : result, cart : request.session.cart });

	});

});

//Create Route for Add Item into Cart
app.post('/add_cart', (request, response) => {

	const product_id = request.body.product_id;

	const product_name = request.body.product_name;

	const product_price = request.body.product_price;

	let count = 0;

	for(let i = 0; i < request.session.cart.length; i++)
	{

		if(request.session.cart[i].product_id === product_id)
		{
			request.session.cart[i].quantity += 1;

			count++;
		}

	}

	if(count === 0)
	{
		const cart_data = {
			product_id : product_id,
			product_name : product_name,
			product_price : parseFloat(product_price),
			quantity : 1
		};

		request.session.cart.push(cart_data);
	}

	response.redirect("/");

});

//Create Route for Remove Item from Shopping Cart
app.get('/remove_item', (request, response) => {

	const product_id = request.query.id;

	for(let i = 0; i < request.session.cart.length; i++)
	{
		if(request.session.cart[i].product_id === product_id)
		{
			request.session.cart.splice(i, 1);
		}
	}

	response.redirect("/");

});

app.listen(3000, () => {

	console.log('Server has started on port number 3000');

});


Under this file first we have import require Node module and then after we have set up require middleware for Node.js Shopping cart application.

Under this Node.js Shopping cart we have use Session for store shopping cart data in Session, so when page has been refresh then shopping cart data will be removed from this Node Application. So here in this file we have also set up Session middleware for store Shopping cart data.

After this we have make MySQL database connection and then after we have test that our Node.js shopping cart application has been connection with MySQL database.

Under this file we have create three route for handle shopping cart action.

First is the "/" route when has been use get() method and under this route we have fetch data from product table and send that data to product view file. Under this route we have also create cart session variable if it is not created.

Second route is "/add_cart" which has been use post() method. This route has receive data from Add to cart form. So when we have add item into cart by click on Add to cart button then this route will receive Item data which has been store in shopping cart. But suppose particular item data already exists in cart session variable then it will increase that product quantity by 1. And lastly it will redirect web page to display list of product with shopping cart data.

And last route is "/remove_item" which has been use get() method and this route is receive query for remove item from shopping cart. So under this route it has receive item id in url and based on that id value it will remove that id item from shopping cart and it will redirect web page to display all product with remaning shopping cart data on web page.

Step 4: Create Views File


In Node Express framework we have use EJS template for display HTML output in the browser. So in Node Express framework we have to create views directory under our Node Application and under that directory we have to create product.ejs file and under this file we have to write following code.

views/product.ejs

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Node.js Tutorial - Simple Shopping Cart</title>
    <link href="https://getbootstrap.com/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
    <div class="container-fluid mt-5 mb-5">
        <h1 class="text-center"><b>Node.js Tutorial - Simple Shopping Cart</b></h1>
        <div class="mt-3 mb-3">
            <div class="row">
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header"><b>Product List</b></div>
                        <div class="card-body">
                            <div class="row">
                                <% products.forEach(product => { %>
                                <div class="col-md-4 mb-5 text-center">
                                    <img src="/images/<%= product.product_image %>" class="img-thumbnail mb-3" />
                                    <h4><b><%= product.product_name %></b></h4>
                                    <h3 class="text-danger"><%= product.product_price %></h3>
                                    <form method="post" action="/add_cart">
                                        <input type="hidden" name="product_id" value="<%= product.product_id %>" />

                                        <input type="hidden" name="product_name" value="<%= product.product_name %>" />

                                        <input type="hidden" name="product_price" value="<%= product.product_price %>" />

                                        <input type="submit" class="btn btn-warning" value="Add to Cart" />
                                    </form>
                                </div>
                                <% }) %>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-header"><b>Shopping Cart</b></div>
                        <div class="card-body">
                            <table class="table">
                                <tr>
                                    <th>Item Name</th>
                                    <th>Quantity</th>
                                    <th>Unit Price</th>
                                    <th>Total Price</th>
                                    <th>Remove</th>
                                </tr>
                                <% 
                                if(cart.length > 0)
                                {
                                    let total = 0;

                                    cart.forEach(item => {
                                %>
                                <tr>
                                    <td><%= item.product_name %></td>
                                    <td><%= item.quantity %></td>
                                    <td><%= item.product_price %></td>
                                    <td><%= parseFloat(item.quantity) * parseFloat(item.product_price) %></td>
                                    <td><button type="button" class="btn btn-danger btn-sm" onclick="remove_item(<%= item.product_id %>)">Remove</button></td>
                                </tr>
                                <%
                                        total += parseFloat(item.quantity) * parseFloat(item.product_price);
                                    })
                                %>
                                <tr>
                                    <td colspan="3" aling="right"><b>Total</b></td>
                                    <td><%= total %></td>
                                    <td>&nbsp;</td>
                                </tr>
                                <%
                                }
                                else
                                {
                                %>

                                <tr>
                                    <td colspan="5" align="center">No Item Found in Cart</td>
                                </tr>

                                <%
                                }
                                %>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <br />
            
        </div>
    </div>
</body>
</html>

<script>

    function remove_item(item_id)
    {
        if(confirm("Are you sure you want to remove it?"))
        {
            window.location.href = `/remove_item?id=${item_id}`;
        }
    }

</script>


This code is the view template for the product page. The page displays a list of products with their respective images, names, and prices. For each product, there is a form to add the product to the shopping cart. The shopping cart is also displayed on the same page on the right side of the screen. The shopping cart shows the list of items added to the cart with their respective quantities, unit prices, and total prices.

The shopping cart also provides a remove button to remove an item from the cart. The function remove_item is defined in the script tag that removes the item from the cart by sending a request to the server with the item's ID.

The page is designed using Bootstrap 5 CSS classes, with a container-fluid and a row for the main content, and two columns for the product list and the shopping cart, respectively. The product list is created using a loop that iterates over each product in the products array and displays their information using EJS syntax. The shopping cart is also created using a loop that iterates over each item in the cart array and displays their information. If the cart is empty, the page shows a message indicating that no items have been added to the cart.

Conclusion


Overall, creating a shopping cart in Node.js is a relatively easy task, and with the help of this tutorial, you can create a shopping cart for your Node.js application.





Friday, 24 March 2023

How to make Contact Form in Node.js

Node.js Tutorial on Server-side Form Validation



How to Send an Email in Node.js using Nodemailer



In this tutorial, we will learn how to make a contact form in Node.js and how to server-side validate form data and send an email from Node.js application.

To create a contact form in Node.js, we will be using the following technologies:

  • Express: Express is a Node.js web application framework that provides a set of features for building web applications.
  • Body-parser: Body-parser is a Node.js middleware that parses incoming request bodies in a middleware before your handlers, available under the req.body property.
  • Express-validator: Express-validator is a set of express.js middlewares that wraps validator.js validator and sanitizer functions.
  • Nodemailer: Nodemailer is a module for Node.js applications that allows you to send emails from your application.

How to make Contact Form in Node.js


Let's start by installing these dependencies using the following command:


npm install express body-parser express-validator nodemailer ejs


Next, create a file named app.js and add the following code:


const express = require('express');

const bodyParser = require('body-parser');

const { check, validationResult } = require('express-validator');

const nodemailer = require('nodemailer');

const ejs = require('ejs');

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.set('view engine', 'ejs');

//middleware for parsing JSON in request body
app.use(express.json());

app.get('/', (request, response) => {

	response.render('contact', { errors : '' });

});

app.post('/send', 
	[
		check('name').notEmpty().withMessage('Name is required'),
		check('email').isEmail().withMessage('Invalid Email Address'),
		check('subject').notEmpty().withMessage('Subject is required'),
		check('message').notEmpty().withMessage('Message is required')
	], (request, response) => {

		const errors = validationResult(request);

		if(!errors.isEmpty())
		{
			response.render('contact', { errors : errors.mapped() });
		}
		else
		{
			const transporter = nodemailer.createTransport({
				service : 'Gmail',
				auth : {
					user : 'povonteblog@gmail.com',
					pass : 'write your Google App Password'
				}
			});

			const mail_option = {
				from : request.body.email,
				to : 'jm6078390@gmail.com',
				subject : request.body.subject,
				text : request.body.message
			};

			transporter.sendMail(mail_option, (error, info) => {
				if(error)
				{
					console.log(error);
				}
				else
				{
					response.redirect('/success');
				}
			});
		}
});

app.get('/success', (request, response) => {

	response.send('<h1>Your Message was Successfully Send!</h1>');

});

//start server
app.listen(3000, () => {

	console.log('Server started on port 3000');

});





Here, we have defined a GET route for rendering the contact form using ejs view engine. And, we have defined a POST route for processing the form data.

In the POST route, we have used express-validator to validate the form data. If there are any validation errors, we render the contact view with the error messages. Otherwise, we use nodemailer to send an email to the recipient email address.

Let's create a contact.ejs view file under the views folder with the following code:


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Node.js Server Side Validation</title>
    <link href="https://getbootstrap.com/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5 mb-5">
        <h1 class="text-warning text-center"><b>Node.js Tutorial - How to Send an Email</b></h1>
        <div class="col-md-6 mt-3 mb-3">
            <div class="card">
                <div class="card-header">Contact Form</div>
                <div class="card-body">

                    <form method="post" action="/send">
                        <div class="mb-3">
                            <label for="name">Name</label>
                            <input type="text" name="name" class="form-control" />
                            <% if(errors && errors.name) { %>
                            <span class="text-danger"><%= errors.name.msg %></span>
                            <% } %>
                        </div>
                        <div class="mb-3">
                            <label for="email">Email</label>
                            <input type="text" name="email" class="form-control" />
                            <% if (errors && errors.email) { %>
                            <span class="text-danger"><%= errors.email.msg %></span>
                            <% } %>
                        </div>
                        <div class="mb-3">
                            <label for="subject">Subject</label>
                            <input type="text" name="subject" class="form-control" />
                            <% if (errors && errors.subject) { %>
                            <span class="text-danger"><%= errors.subject.msg %></span>
                            <% } %>
                        </div>
                        <div class="mb-3">
                            <label for="message">Message</label>
                            <textarea name="message" class="form-control"></textarea>
                            <% if(errors && errors.message) { %>
                            <span class="text-danger"><%= errors.message.msg %></span>
                            <% } %>
                        </div>
                        <button type="submit" class="btn btn-success">Send Message</button>
                    </form>

                </div>
            </div>
        </div>
    </div>
</body>
</html>


In this view file, we have created a simple HTML form with fields for name, email, subject, and message. We have also used Bootstrap classes for styling the form.

We have also added a condition in the view to check if there are any validation errors. If there are any errors, we will display the error message next to the corresponding field.

Conclusion


In this tutorial, we learned how to create a contact form using Node.js in which we have cover how to validate the form data on the server-side. We used the Express.js framework and the Nodemailer package to send an email from the Node.js application.

Server-side validation of form data is essential to prevent invalid or malicious data from being submitted to the server. Nodemailer is a powerful package that can be used to send emails from Node.js applications.

With this knowledge, you can now create more complex forms and implement server-side validation for them and sending an email from Node.js Application.

Saturday, 18 March 2023

Node.js and MySQL: How to Load More Data with Ajax

Node.js is a popular server-side JavaScript runtime that enables developers to build scalable, high-performance applications. One of the most common use cases for Node.js is building web applications that require real-time updates, such as social media platforms, chat applications, and news portals. These applications often require the ability to fetch and display large amounts of data on-demand, without refreshing the entire page. This is where Ajax comes in.

Ajax stands for Asynchronous JavaScript and XML, and it allows web pages to update content dynamically without requiring a full page reload. In this tutorial, we will explore how to use Ajax with Node.js and MySQL to load more data on-demand, without requiring a full page refresh.

We will build a simple application that fetches and displays post titles from a MySQL database. The user will be able to click a "Load More" button to fetch additional post titles on-demand, without refreshing the page.


Node.js and MySQL: How to Load More Data with Ajax


Prerequisites


To follow along with this tutorial, you should have a basic understanding of Node.js and MySQL. You will also need to have Node.js and MySQL installed on your machine.

Setting up the project


Create a new directory for your project and navigate to it in the terminal. Initialize a new Node.js project by running the following command:


npm init


Follow the prompts to set up your project. Once you have initialized your project, install the following dependencies:


npm install express mysql


First we have to create one table in your MySQL database, so for create table you can run below .SQL script which will create post and insert sample data into that table. So you can easily practice this tutorial in your local computer.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `post`
--

CREATE TABLE `post` (
  `id` mediumint(8) UNSIGNED NOT NULL DEFAULT '0',
  `post_title` text
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `post`
--

INSERT INTO `post` (`id`, `post_title`) VALUES
(1, 'Insert Update Delete using Stored Procedure in Mysql and PHP - 1'),
(2, 'Insert Update Delete using Stored Procedure in Mysql and PHP - 2'),
(3, 'Insert Update Delete using Stored Procedure in Mysql and PHP - 3 '),
(4, 'Auto Refresh Div Content Using jQuery and AJAX'),
(5, 'How to generate simple random password in php?'),
(6, 'Rename uploaded image in php with upload validation'),
(7, 'How to check Username availability using php, Ajax, Jquery and Mysql'),
(8, 'How To Insert Data Using Stored Procedure In Php Mysql'),
(9, 'How to merge two PHP JSON Array'),
(10, 'How to check Multiple value exists in an Array in PHP'),
(11, 'Create Simple Image using PHP'),
(12, 'How to Add Watertext or Watermark to an Image using PHP GD Library'),
(13, 'Make SEO Friendly or Clean Url in PHP using .htaccess'),
(14, 'Live Table Add Edit Delete using Ajax Jquery in PHP Mysql'),
(15, 'Export MySQL data to Excel in PHP - PHP Tutorial'),
(16, 'Load More Data using Ajax Jquery with PHP MySql'),
(17, 'Dynamically Add / Remove input fields in PHP with Jquery Ajax'),
(18, 'PHP Introduction - PHP Tutorial for Beginner'),
(19, 'PHP Variables - Echo, Print statement - PHP Tutorial for Beginner'),
(20, 'How to Import Excel Data into MySQL Database using PHP'),
(21, 'Convert Currency using Google Finance in PHP'),
(22, 'Dynamic Dependent Select Box using Jquery and Ajax in PHP'),
(23, 'How to use HTML tag into PHP tag'),
(24, 'How to use PHP code into HTML Tag'),
(25, 'How to get Multiple Checkbox values in php'),
(26, 'Ajax Live Data Search using Jquery PHP MySql'),
(27, 'Auto Save Data using Ajax, Jquery, PHP and Mysql'),
(28, 'How to Use Ajax with PHP for login with shake effect'),
(29, 'How to get Time Ago like Facebook in PHP'),
(30, 'Upload Resize Image using Ajax Jquery PHP without Page Refresh'),
(31, 'How to Search for Exact word match FROM String using LIKE'),
(32, 'How To Create A Show Password Button using Jquery'),
(33, 'Use Marquee HTML tag with PHP and Mysql - PHP Tutorial'),
(34, 'How to Enter PHP Array within MySQL Database'),
(35, 'Use Ajax with Jquery in PHP to check Session Expired'),
(36, 'Ajax Delete multiple data with checkboxes in PHP Jquery Mysql'),
(37, 'Automatic Logout after 15 minutes of user Inactivity using PHP'),
(38, 'PHP Login Script with Remember me Login Details'),
(39, 'Arithmetic Operators - PHP Beginner Tutorial'),
(40, 'Shorten Dynamic Comment with Jquery PHP Mysql'),
(41, 'If, If else Conditional Statement in PHP'),
(42, 'If, Else if Conditional statement in PHP'),
(43, 'How to Create Zip File using PHP Code'),
(44, 'Increment / Decrement Operator - PHP Beginner Tutorial'),
(45, 'How to Generate CSV File from PHP Array'),
(46, 'Upload CSV and Insert Data into Mysql Using PHP'),
(47, 'Multiple Images Upload using PHP Jquery Ajax'),
(48, 'Fetch JSON Data & Insert into Mysql table in PHP'),
(49, 'Comparison Operators - PHP Beginner Tutorial'),
(50, 'Create Simple Progress bar using HTML, CSS with jquery'),
(51, 'Append Data to JSON File using PHP'),
(52, 'Form Submit with Fade Out Message using Jquery Ajax PHP'),
(53, 'String Operators - PHP Beginner Tutorial'),
(54, 'Load Records on Select box using Ajax Jquery Mysql and PHP'),
(55, 'Fetch Data from Two or more Table Join using PHP and MySql'),
(56, 'Convert Data from Mysql to JSON Formate using PHP'),
(57, 'How to use Mysql View in PHP Code'),
(58, 'Upload and Extract a Zip File in PHP'),
(59, 'Stylish Switch Button using CSS3 and Jquery'),
(60, 'How to create Spinner or Loaders with CSS3'),
(61, 'How to Auto Resize a textarea html field by jQuery'),
(62, 'Insert data into Table using OOPS in PHP'),
(63, 'Select or Fetch Data from Mysql Table using OOPS in PHP'),
(64, 'Update or Edit Data from Mysql Table using OOPS in PHP'),
(65, 'Delete Data from Mysql Table using OOP in PHP'),
(66, 'PHP Login Script using OOP'),
(67, 'How to load Product on price change using Ajax Jquery with PHP Mysql'),
(68, 'How to Make Simple Pagination using PHP MySql'),
(69, 'PHP MySQL Insert record if not exists in table'),
(70, 'How to search multiple words at a time in Mysql php'),
(71, 'How to load data from json file in php'),
(72, 'Load JSON Data using Ajax getJSON Method'),
(73, 'Add smooth scrolling by using Jquery Animate method'),
(74, 'Ajax Autocomplete textbox using jQuery, PHP and MySQL'),
(75, 'Jquery Insert Form Data using Ajax serialize() method with php mysql'),
(76, 'Insert Form data using Jquery Post() Method with PHP Mysql'),
(77, 'Connect MySQL Database in PHP via PDO - PHP Data Object'),
(78, 'Insert data into Mysql in PHP using PDO - PHP Data Object'),
(79, 'Fetch Data from Mysql in PHP using PDO - PHP Data Object'),
(80, 'PDO (PHP Data Object) - Edit / Update Mysql Table data in PHP'),
(81, 'PDO (PHP Data Object) - Delete Mysql Table data in PHP'),
(82, 'PHP Login Script using PDO with Session'),
(83, 'PHP Jquery Ajax : Insert Radio Button value on click'),
(84, 'How to Count a Array of Specific Words from String in PHP'),
(85, 'Create dynamic JSON file in PHP Mysql'),
(86, 'Insert Checkbox values using Ajax Jquery in PHP'),
(87, 'How to Remove file from Server in PHP Programming Language'),
(88, 'PHP Tutorial - Find the number of days, hours, minutes and seconds between two dates'),
(89, 'Displaying text in Vertical Direction by using CSS with HTML'),
(90, 'Show JSON Data in Jquery Datatables'),
(91, 'Sliding Text on Images by using Jquery'),
(92, 'How to Make Horizontal Menu using CSS and Jquery'),
(93, 'How to make flashing button with CSS3 keyframes Animation'),
(94, 'Get Maximum Numeric value from Associative Array in PHP'),
(95, 'How to make Zebra Stripes Table with PHP Mysql'),
(96, 'How to Get File Extension in PHP'),
(97, 'Server Side Form Validation in PHP Programming Language'),
(98, 'PHP Array Functions - array() Function'),
(99, 'PHP Array Functions - array_change_key_case() Function'),
(100, 'PHP Array Functions - array_chunk() Function');
COMMIT;


We will use the Express.js framework to create a simple web server, and the mysql package to connect to our MySQL database.

Create a new file called server.js, and add the following code:


const express = require('express');
const mysql = require('mysql');
const application = express();

const connection = mysql.createConnection({
  host : 'localhost',
  user : 'root',
  password : '',
  database : 'testing'
});

application.get("/", (request, response) => {
  response.sendFile(__dirname + '/index.html');
});

application.get("/get_data", (request, response) => {
  const start_index = request.query.start_index;
  const number_of_record = request.query.num_record;
  const sql = `SELECT post_title FROM post ORDER BY id ASC LIMIT ${start_index}, ${number_of_record}`;
  connection.query(sql, (error, results) => {
    response.json(results);
  });
});

application.listen(3000, () => {
  console.log('Server started on port 3000');
});





This code sets up a new Express.js application and creates a new MySQL connection. It also sets up two routes - the "/" route, which serves our HTML file, and the "/get_data" route, which fetches post titles from the database and sends them back to the client as a JSON response.

Create a new file called index.html, and add the following code:


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Load More Data using Ajax with Node.js & MySQL</title>
    <link href="https://getbootstrap.com/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5 mb-5">
        <h1 class="text-primary text-center"><b>Load More Data using Ajax with Node.js & MySQL</b></h1>
        <div class="mt-3 mb-3">
            <div class="card">
                <div class="card-header">Post Data</div>
                <div class="card-body">
                    <ul class="list-group mb-3" id="post_data">

                    </ul>

                    <button type="button" class="btn btn-primary" id="load_button">Load More</button>
                </div>
            </div>
        </div>
    </div>

    <script>

        //npm install express mysql

        const post_data = document.querySelector('#post_data');

        const load_button = document.querySelector('#load_button');

        var start_index = 0;

        var number_of_record = 10;

        load_data();

        load_button.addEventListener('click', () => {

            load_data();

        });

        function load_data()
        {
            load_button.innerHTML = 'wait...';

            load_button.disabled = true;

            setTimeout(function(){

                const request = new XMLHttpRequest();

                request.open('GET', `/get_data?start_index=${start_index}&num_record=${number_of_record}`);

                request.onload = () => {

                    const results = JSON.parse(request.responseText);

                    let html = '';

                    if(results.length > 0)
                    {
                        results.forEach(result => {

                            html += '<li class="list-group-item">' + result.post_title + '</li>';

                            start_index++;

                            console.log(start_index);

                        });

                        load_button.innerHTML = 'Load More';

                        load_button.disabled = false;
                    }
                    else
                    {
                        html += '<li class="list-group-item active">No More Data Found</li>';

                        load_button.remove();
                    }

                    post_data.innerHTML = post_data.innerHTML + html;

                    window.scrollTo(0, document.body.scrollHeight);
                };

                request.send();

            }, 1000);
        }

    </script>
</body>
</html>


To make use of this code, you need to create an HTML file where you will include the necessary JavaScript code. In this example, we have created an index.html file that includes the Bootstrap CSS library.

The HTML file has a container with a card that has a header called "Post Data." Under the header, we have a list group with an ID called "post_data" where we will append the fetched data. Below the list group, we have a button with an ID called "load_button" that will be used to load more data.

In the JavaScript code, we start by selecting the list group and the button element using the document.querySelector method. We also set the start_index and number_of_record variables to 0 and 10, respectively, and then we call the load_data function with these parameters.

The load_data function sets the load_button text to "wait..." and disables the button to prevent multiple clicks. We then create a new XMLHttpRequest object and set the request URL to "/get_data" with the start_index and num_record parameters. We also set the onload event handler to parse the JSON response and append the results to the list group. We then set the load_button text to "Load More" and enable the button. If the results array is empty, we append a message to the list group indicating that there is no more data to load and remove the button.

Finally, we append the HTML content to the list group and scroll to the bottom of the page. When the user clicks the load_button, the load_data function is called again, but with an updated start_index parameter, which fetches the next set of data.

In conclusion, by using Node.js and MySQL together, you can easily load more data with Ajax. This technique can be useful when working with large datasets or when you want to minimize the initial load time of your page. By following the steps outlined in this article and by modifying the code to fit your specific needs, you can create a dynamic and responsive website that will impress your users.