<?xml version="1.0" encoding="UTF-8" standalone="no"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" version="2.0">

<channel>
	<title>Tech Arise</title>
	<atom:link href="https://techarise.com/feed/" rel="self" type="application/rss+xml"/>
	<link>https://techarise.com</link>
	<description>Web Development Tutorials &amp; Resources</description>
	<lastBuildDate>Mon, 01 Jan 2024 11:07:11 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<itunes:explicit>no</itunes:explicit><itunes:image href="http://techarise.com/wp-content/themes/zbench/images/logo.png"/><itunes:keywords>Apple,iPad,iPhones,iPod,Mac,Bikes,Bajaj,Honda,Mahindra,Suzuki,TVS,Yamaha,Cars,Ford,Hyundai,Mahindra,Tata,Computers,Dell,HP,Lenovo,LG,Zenth,Laptops,Acer,Compaq,Dell,HCL,HP,Lenovo,Samsung,Sony,Mobile,Phone,Acer,Alcatel,BlackBerry,HTC,Huawei,Lava,LG,Mic</itunes:keywords><itunes:summary>Apple,iPad,iPhones,iPod,Mac, Bikes,Bajaj,Honda,Mahindra,Suzuki,TVS,Yamaha, Cars,Ford,Hyundai,Mahindra,Tata, Computers,Dell,HP,Lenovo,LG,Zenth, Laptops,Acer,Compaq,Dell,HCL,HP,Lenovo,Samsung,Sony, Mobile Phone,Acer,Alcatel,BlackBerry,HTC,Huawei,Lava,LG,Micromax,Motorola,Nokia,Samsung,Sony Ericsson,Spice,Videocon, Tablet,Fujitsu,MSI,Reliance,Toshiba</itunes:summary><itunes:subtitle>Apple,iPad,iPhones,iPod,Mac, Bikes,Bajaj,Honda,Mahindra,Suzuki,TVS,Yamaha, Cars,Ford,Hyundai,Mahindra,Tata, Computers,Dell,HP,Lenovo,LG,Zenth, Laptops,Acer,Compaq,Dell,HCL,HP,Lenovo,Samsung,Sony, Mobile Phone,Acer,Alcatel,BlackBerry,HTC,Huawei,Lava,LG,Mic</itunes:subtitle><itunes:category text="Technology"><itunes:category text="Tech News"/></itunes:category><itunes:owner><itunes:email>techariseinfo@gmail.com</itunes:email></itunes:owner><item>
		<title>Library Management System in PHP and MySQL</title>
		<link>https://techarise.com/library-management-system-in-php-and-mysql/</link>
		
		
		<pubDate>Mon, 01 Jan 2024 10:05:28 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">https://techarise.com/?p=1470</guid>

					<description><![CDATA[<p>The Library Management System is a web-based system used in a library to manage items. It is a software system&#8230;</p>
<p>The post <a href="https://techarise.com/library-management-system-in-php-and-mysql/">Library Management System in PHP and MySQL</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></description>
										<content:encoded><![CDATA[<div class="new-line-label">The Library Management System is a web-based system used in a library to manage items. It is a software system that helps in maintaining records of all library. A library management system is a Digital library software that keeps track of each book issued, returned, and added to the library.</div>

<div class="new-line-label">You can find books in an instant, issue/reissue books quickly, and manage all the data efficiently and orderly using this system. The purpose of a library management system is to provide instant and accurate data regarding any type of book, thereby saving a lot of time and effort.</div>

<div class="new-line-label">In this tutorial, you will learn to how manage Library Management System in PHP and MySQL. This is a very simple example, you can just copy-paste, and change it according to your requirements.</div>

<div class="ex-read-more new-line-label">
    <a href="https://techarise.com/build-simple-rest-api-with-php-mysql/" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
           Also Read : Build Simple REST API with PHP and MySQL
        </div>
    </a>
</div>

<div class="top-line-bold">Before started to implement the Library Management System in PHP and MySQL, look files structure:</div>

<ul class="tree-structure"> 
  <li><i class="folder-color fa fa-folder"></i> library-management-system
  
      <ul>
        <li><i class="folder-color fa fa-folder"></i> config
          <ul>
             <li><i class="text-muted far fa-file"></i> Config.php</li>
        </ul>
        </li>

        <li><i class="folder-color fa fa-folder"></i> class
          <ul>
             <li><i class="text-muted far fa-file"></i> Author.php</li>
             <li><i class="text-muted far fa-file"></i> Books.php</li>
             <li><i class="text-muted far fa-file"></i> Category.php</li>
             <li><i class="text-muted far fa-file"></i> IssueBooks.php</li>
             <li><i class="text-muted far fa-file"></i> Publisher.php</li>
             <li><i class="text-muted far fa-file"></i> Rack.php</li>
             <li><i class="text-muted far fa-file"></i> User.php</li>
        </ul>
        </li>

        <li><i class="folder-color fa fa-folder"></i> templates
          <ul>
             <li><i class="text-muted far fa-file"></i> footer.php</li>
             <li><i class="text-muted far fa-file"></i> header.php</li>
             <li><i class="text-muted far fa-file"></i> left_menus.php</li>
             <li><i class="text-muted far fa-file"></i> menus.php</li>
        </ul>
        </li>

        <li><i class="folder-color fa fa-folder"></i> css
          <ul>
             <li><i class="text-muted far fa-file"></i> style.css</li>
        </ul>
        </li> 

        <li><i class="folder-color fa fa-folder"></i> js
          <ul>
             <li><i class="text-muted far fa-file"></i> </li>
        </ul>
        </li> 

        <li><i class="folder-color fa fa-folder"></i> images
          <ul>
             <li><i class="text-muted far fa-file"></i> author.js</li>
             <li><i class="text-muted far fa-file"></i> books.js</li>
             <li><i class="text-muted far fa-file"></i> category.js</li>
             <li><i class="text-muted far fa-file"></i> issue_books.js</li>
             <li><i class="text-muted far fa-file"></i> publisher.js</li>
             <li><i class="text-muted far fa-file"></i> rack.js</li>
             <li><i class="text-muted far fa-file"></i> user.js</li>
        </ul>
        </li> 

        <li><i class="folder-color fa fa-folder"></i> popup
          <ul>
             <li><i class="text-muted far fa-file"></i> add-author.php</li>
             <li><i class="text-muted far fa-file"></i> add-book.php</li>
             <li><i class="text-muted far fa-file"></i> add-category.php</li>
             <li><i class="text-muted far fa-file"></i> add-issue-books.php</li>
             <li><i class="text-muted far fa-file"></i> add-publisher.php</li>
             <li><i class="text-muted far fa-file"></i> add-rack.php</li>
             <li><i class="text-muted far fa-file"></i> add-user.php</li>
        </ul>
        </li> 

      </ul>      
    </li> 
    <li><i class="text-muted far fa-file"></i> author.php</li> 
    <li><i class="text-muted far fa-file"></i> author_action.php</li>
    <li><i class="text-muted far fa-file"></i> books.php</li>
    <li><i class="text-muted far fa-file"></i> books_action.php</li>
    <li><i class="text-muted far fa-file"></i> category.php</li>
    <li><i class="text-muted far fa-file"></i> category_action.php</li>
    <li><i class="text-muted far fa-file"></i> dashboard.php</li>
    <li><i class="text-muted far fa-file"></i> index.php</li>
    <li><i class="text-muted far fa-file"></i> issue_books.php</li>
    <li><i class="text-muted far fa-file"></i> issue_books_action.php</li>
    <li><i class="text-muted far fa-file"></i> logout.php</li>
    <li><i class="text-muted far fa-file"></i> publisher.php</li>
    <li><i class="text-muted far fa-file"></i> publisher_action.php</li>
    <li><i class="text-muted far fa-file"></i> rack.php</li>
    <li><i class="text-muted far fa-file"></i> rack_action.php</li>
    <li><i class="text-muted far fa-file"></i> user.php</li>
    <li><i class="text-muted far fa-file"></i> user_action.php</li>
  </ul>

<div class="top-line-bold">Features of library management system:</div>
<ul style="padding-left:30px;">
    <li>Users/Members records Management</li>
	<li>Category records Management</li>
	<li>Author/Writer records Management</li>
	<li>Publisher records Management</li>
	<li>Rack records Management</li>
	<li>Book records Management</li>
	<li>Issue Books records Management</li>	
</ul>


<div class="top-line-bold">Step 1: Create the Database and Table</div>
<div class="new-line-label">For this tutorial, you need a MySQL database with the following tables:</div>

<div class="new-line-label">Create <code>user</code> table to store user login details.</div>
<pre class="crayon-plain-tag">CREATE TABLE `user` (
      `id` int(11) UNSIGNED NOT NULL,
      `first_name` varchar(255) DEFAULT NULL,
      `last_name` varchar(255) DEFAULT NULL,
      `email` varchar(255) DEFAULT NULL,
      `password` varchar(64) NOT NULL,
      `role` enum('admin','user') DEFAULT 'admin'
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

    ALTER TABLE `user`
      ADD PRIMARY KEY (`id`);

    ALTER TABLE `user`
      MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT;</pre>

<div class="new-line-label">Create <code>book </code> table to store books details.</div>
<pre class="crayon-plain-tag">CREATE TABLE `book` (
      `bookid` int(11) NOT NULL,
      `categoryid` int(11) NOT NULL,
      `authorid` int(11) NOT NULL,
      `rackid` int(11) NOT NULL,
      `name` text NOT NULL,
      `picture` varchar(250) NOT NULL,
      `publisherid` int(11) NOT NULL,
      `isbn` varchar(30) NOT NULL,
      `no_of_copy` int(5) NOT NULL,
      `status` enum('Enable','Disable') NOT NULL,
      `added_on` datetime NOT NULL DEFAULT current_timestamp(),
      `updated_on` datetime NOT NULL DEFAULT current_timestamp()
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

    ALTER TABLE `book`
      ADD PRIMARY KEY (`bookid`);

    ALTER TABLE `book`
      MODIFY `bookid` int(11) NOT NULL AUTO_INCREMENT;</pre>

<div class="new-line-label">Create <code>author</code> table to store book author details.</div>
<pre class="crayon-plain-tag">CREATE TABLE `author` (
      `authorid` int(11) NOT NULL,
      `name` varchar(200) NOT NULL,
      `status` enum('Enable','Disable') NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

    ALTER TABLE `author`
      ADD PRIMARY KEY (`authorid`);

    ALTER TABLE `author`
      MODIFY `authorid` int(11) NOT NULL AUTO_INCREMENT;</pre>

<div class="new-line-label">Create <code>publisher </code> table to store publisher details.</div>
<pre class="crayon-plain-tag">CREATE TABLE `publisher` (
      `publisherid` int(11) NOT NULL,
      `name` varchar(255) NOT NULL,
      `status` enum('Enable','Disable') NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

    ALTER TABLE `publisher`
      ADD PRIMARY KEY (`publisherid`);

    ALTER TABLE `publisher`
      MODIFY `publisherid` int(11) NOT NULL AUTO_INCREMENT;</pre>

<div class="new-line-label">Create <code>category </code> table to store book category details.</div>
<pre class="crayon-plain-tag">CREATE TABLE `category` (
      `categoryid` int(11) NOT NULL,
      `name` varchar(200) NOT NULL,
      `status` enum('Enable','Disable') NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
   
    ALTER TABLE `category`
      ADD PRIMARY KEY (`categoryid`);

    ALTER TABLE `category`
      MODIFY `categoryid` int(11) NOT NULL AUTO_INCREMENT;</pre>

<div class="new-line-label">Create <code>rack </code> table to store book location details.</div>
<pre class="crayon-plain-tag">CREATE TABLE `rack` (
      `rackid` int(11) NOT NULL,
      `name` varchar(200) NOT NULL,
      `status` enum('Enable','Disable') NOT NULL DEFAULT 'Enable'
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

    ALTER TABLE `rack`
      ADD PRIMARY KEY (`rackid`);

    ALTER TABLE `rack`
      MODIFY `rackid` int(11) NOT NULL AUTO_INCREMENT;</pre>

<div class="new-line-label">Create <code>issued_book </code> table to store book issue details.</div>
<pre class="crayon-plain-tag">CREATE TABLE `issued_book` (
      `issuebookid` int(11) NOT NULL,
      `bookid` int(11) NOT NULL,
      `userid` int(11) NOT NULL,
      `issue_date_time` datetime NOT NULL DEFAULT current_timestamp(),
      `expected_return_date` datetime NOT NULL,
      `return_date_time` datetime NOT NULL,
      `status` enum('Issued','Returned','Not Return') NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

    ALTER TABLE `issued_book`
      ADD PRIMARY KEY (`issuebookid`);

    ALTER TABLE `issued_book`
      MODIFY `issuebookid` int(11) NOT NULL AUTO_INCREMENT;</pre>

<div class="top-line-bold">Create a Database configuration file named <code>Config.php</code> inside config/ folder</div>
<pre class="crayon-plain-tag">&lt;?php

/**
 * Description of Config Class
 *
 * @author Team TechArise
 *
 * @email info@techarise.com
 */

session_start();
class Config
{

    private $host  = 'localhost';
    private $user  = 'root';
    private $password   = &quot;&quot;;
    private $database  = &quot;lms_DB&quot;;

    public function getConnection()
    {
        $conn = new mysqli($this-&gt;host, $this-&gt;user, $this-&gt;password, $this-&gt;database);
        if ($conn-&gt;connect_error) {
            die(&quot;Error failed to connect to MySQL: &quot; . $conn-&gt;connect_error);
        } else {
            return $conn;
        }
    }
}
?&gt;</pre>

<div class="top-line-bold">Step 2: Create/Manage Users</div>

<div class="new-line-label">i- Create a class file named <code>User.php</code> inside class/ folder.</div>
<pre class="crayon-plain-tag">&lt;?php

/**
 * Description of User Class
 *
 * @author Team TechArise
 *
 * @email info@techarise.com
 */

class User
{

    private $userTable = 'user';
    private $conn;

    public function __construct($db)
    {
        $this-&gt;conn = $db;
    }

    public function login()
    {
        if ($this-&gt;email &amp;&amp; $this-&gt;password) {
            $sqlQuery = &quot;
                SELECT * FROM &quot; . $this-&gt;userTable . &quot; 
                WHERE email = ? AND password = ?&quot;;
            $stmt = $this-&gt;conn-&gt;prepare($sqlQuery);
            $password = md5($this-&gt;password);
            $stmt-&gt;bind_param(&quot;ss&quot;, $this-&gt;email, $password);
            $stmt-&gt;execute();
            $result = $stmt-&gt;get_result();
            if ($result-&gt;num_rows &gt; 0) {
                $user = $result-&gt;fetch_assoc();
                $_SESSION[&quot;userid&quot;] = $user['id'];
                $_SESSION[&quot;role&quot;] = $user['role'];
                $_SESSION[&quot;name&quot;] = ucfirst($user['first_name']) . &quot; &quot; . ucfirst($user['last_name']);;
                $_SESSION[&quot;email&quot;] = $user['email'];
                return 1;
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    public function loggedIn()
    {
        if (!empty($_SESSION[&quot;userid&quot;])) {
            return 1;
        } else {
            return 0;
        }
    }

    public function isAdmin()
    {
        if (!empty($_SESSION[&quot;userid&quot;]) &amp;&amp; $_SESSION[&quot;role&quot;] == 'admin') {
            return 1;
        } else {
            return 0;
        }
    }

    public function listUsers()
    {

        $sqlQuery = &quot;SELECT id, first_name, last_name, email, password, role
            FROM &quot; . $this-&gt;userTable . &quot; &quot;;

        if (!empty($_POST[&quot;search&quot;][&quot;value&quot;])) {
            $sqlQuery .= ' WHERE (id LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
            $sqlQuery .= ' OR first_name LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
            $sqlQuery .= ' OR email LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
            $sqlQuery .= ' OR password LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
            $sqlQuery .= ' OR role LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
        }

        if (!empty($_POST[&quot;order&quot;])) {
            $sqlQuery .= 'ORDER BY ' . $_POST['order']['0']['column'] . ' ' . $_POST['order']['0']['dir'] . ' ';
        } else {
            $sqlQuery .= 'ORDER BY id DESC ';
        }

        if ($_POST[&quot;length&quot;] != -1) {
            $sqlQuery .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
        }

        $stmt = $this-&gt;conn-&gt;prepare($sqlQuery);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();

        $stmtTotal = $this-&gt;conn-&gt;prepare($sqlQuery);
        $stmtTotal-&gt;execute();
        $allResult = $stmtTotal-&gt;get_result();
        $allRecords = $allResult-&gt;num_rows;

        $displayRecords = $result-&gt;num_rows;
        $records = array();
        $count = 1;
        while ($user = $result-&gt;fetch_assoc()) {
            $rows = array();
            $rows[] = $count;
            $rows[] = ucfirst($user['first_name']) . &quot; &quot; . ucfirst($user['last_name']);
            $rows[] = $user['email'];
            $rows[] = $user['role'];
            $rows[] = '&lt;button type=&quot;button&quot; name=&quot;update&quot; id=&quot;' . $user[&quot;id&quot;] . '&quot; class=&quot;btn btn-primary btn-sm update&quot;&gt;&lt;span class=&quot;fa fa-edit&quot; title=&quot;Edit&quot;&gt; Edit&lt;/span&gt;&lt;/button&gt;';
            $rows[] = '&lt;button type=&quot;button&quot; name=&quot;delete&quot; id=&quot;' . $user[&quot;id&quot;] . '&quot; class=&quot;btn btn-danger btn-sm delete&quot; &gt;&lt;span class=&quot;fa fa-trash-o&quot; title=&quot;Delete&quot;&gt; Delete&lt;/span&gt;&lt;/button&gt;';
            $records[] = $rows;
            $count++;
        }

        $output = array(
            &quot;draw&quot;  =&gt;  intval($_POST[&quot;draw&quot;]),
            &quot;iTotalRecords&quot; =&gt;  $displayRecords,
            &quot;iTotalDisplayRecords&quot;  =&gt;  $allRecords,
            &quot;data&quot;  =&gt;  $records
        );

        echo json_encode($output);
    }

    public function insert()
    {
        if ($this-&gt;role &amp;&amp; $this-&gt;email &amp;&amp; $this-&gt;password &amp;&amp; $_SESSION[&quot;userid&quot;]) {
            $stmt = $this-&gt;conn-&gt;prepare(&quot;
                INSERT INTO &quot; . $this-&gt;userTable . &quot;(`first_name`, `last_name`, `email`, `password`, `role`)
                VALUES(?, ?, ?, ?, ?)&quot;);
            $this-&gt;role = htmlspecialchars(strip_tags($this-&gt;role));
            $this-&gt;email = htmlspecialchars(strip_tags($this-&gt;email));
            $this-&gt;first_name = htmlspecialchars(strip_tags($this-&gt;first_name));
            $this-&gt;last_name = htmlspecialchars(strip_tags($this-&gt;last_name));
            $this-&gt;password = md5($this-&gt;password);
            $stmt-&gt;bind_param(&quot;sssss&quot;, $this-&gt;first_name, $this-&gt;last_name, $this-&gt;email, $this-&gt;password, $this-&gt;role);

            if ($stmt-&gt;execute()) {
                return true;
            }
        }
    }

    public function update()
    {

        if ($this-&gt;role &amp;&amp; $this-&gt;email &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $updatePass = '';
            if ($this-&gt;password) {
                $this-&gt;password = md5($this-&gt;password);
                $updatePass = &quot;, password = '&quot; . $this-&gt;password . &quot;'&quot;;
            }

            $stmt = $this-&gt;conn-&gt;prepare(&quot;
                UPDATE &quot; . $this-&gt;userTable . &quot; 
                SET first_name = ?, last_name = ?, email = ?, role = ? $updatePass
                WHERE id = ?&quot;);

            $this-&gt;role = htmlspecialchars(strip_tags($this-&gt;role));
            $this-&gt;email = htmlspecialchars(strip_tags($this-&gt;email));
            $this-&gt;first_name = htmlspecialchars(strip_tags($this-&gt;first_name));
            $this-&gt;last_name = htmlspecialchars(strip_tags($this-&gt;last_name));

            $stmt-&gt;bind_param(&quot;ssssi&quot;, $this-&gt;first_name, $this-&gt;last_name, $this-&gt;email, $this-&gt;role, $this-&gt;id);

            if ($stmt-&gt;execute()) {
                return true;
            }
        }
    }

    public function delete()
    {
        if ($this-&gt;id &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $stmt = $this-&gt;conn-&gt;prepare(&quot;
                DELETE FROM &quot; . $this-&gt;userTable . &quot; 
                WHERE id = ?&quot;);

            $this-&gt;id = htmlspecialchars(strip_tags($this-&gt;id));

            $stmt-&gt;bind_param(&quot;i&quot;, $this-&gt;id);

            if ($stmt-&gt;execute()) {
                return true;
            }
        }
    }

    public function getUserDetails()
    {
        if ($this-&gt;user_id &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $sqlQuery = &quot;
                SELECT id, first_name, last_name, email, password, role
                FROM &quot; . $this-&gt;userTable . &quot;           
                WHERE id = ? &quot;;

            $stmt = $this-&gt;conn-&gt;prepare($sqlQuery);
            $stmt-&gt;bind_param(&quot;i&quot;, $this-&gt;user_id);
            $stmt-&gt;execute();
            $result = $stmt-&gt;get_result();
            $records = array();
            while ($user = $result-&gt;fetch_assoc()) {
                $rows = array();
                $rows['id'] = $user['id'];
                $rows['first_name'] = $user['first_name'];
                $rows['last_name'] = $user['last_name'];
                $rows['email'] = $user['email'];
                $rows['role'] = $user['role'];
                $records[] = $rows;
            }
            $output = array(
                &quot;data&quot;  =&gt;  $records
            );
            echo json_encode($output);
        }
    }

    function getUsersList()
    {
        $stmt = $this-&gt;conn-&gt;prepare(&quot;
        SELECT id, first_name, last_name 
        FROM &quot; . $this-&gt;userTable . &quot; 
        WHERE role = 'user'&quot;);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();
        return $result;
    }

    function getTotalUsers()
    {
        $stmt = $this-&gt;conn-&gt;prepare(&quot;
        SELECT *
        FROM &quot; . $this-&gt;userTable);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();
        return $result-&gt;num_rows;
    }
}
?&gt;</pre>

<div class="new-line-label">ii- Create HTML file named <code>user.php</code></div>
<pre class="crayon-plain-tag">&lt;?php
include_once 'config/Config.php';
include_once 'class/User.php';

$conn = new Config();
$db = $conn-&gt;getConnection();

$user = new User($db);

if (!$user-&gt;loggedIn()) {
    header(&quot;Location: index.php&quot;);
}
include('templates/header.php');
?&gt;
&lt;div class=&quot;container-fluid&quot;&gt;
    &lt;div class=&quot;row&quot;&gt;
        &lt;?php include('templates/left_menus.php'); ?&gt;
        &lt;div class=&quot;col-md-10 col-lg-10&quot;&gt;
            &lt;h2&gt;Users&lt;/h2&gt;
            &lt;div class=&quot;panel-heading&quot;&gt;
                &lt;div class=&quot;row&quot;&gt;
                    &lt;div class=&quot;col-md-10&quot;&gt;
                        &lt;h3 class=&quot;panel-title&quot;&gt;&lt;/h3&gt;
                    &lt;/div&gt;
                    &lt;div class=&quot;col-md-2&quot; align=&quot;right&quot;&gt;
                        &lt;button type=&quot;button&quot; id=&quot;addUser&quot; class=&quot;btn btn-info btn-sm&quot; title=&quot;Add User&quot;&gt;&lt;span class=&quot;fa fa-plus&quot;&gt; Add&lt;/span&gt;&lt;/button&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
            &lt;table id=&quot;userListing&quot; class=&quot;table table-striped table-bordered&quot;&gt;
                &lt;thead&gt;
                    &lt;tr&gt;
                        &lt;th&gt;Sn.&lt;/th&gt;
                        &lt;th&gt;Name&lt;/th&gt;
                        &lt;th&gt;Email&lt;/th&gt;
                        &lt;th&gt;Role&lt;/th&gt;
                        &lt;th&gt;&lt;/th&gt;
                        &lt;th&gt;&lt;/th&gt;
                    &lt;/tr&gt;
                &lt;/thead&gt;
            &lt;/table&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;?php
include('popup/add-user.php');
include('templates/footer.php');
?&gt;</pre>

<div class="new-line-label">iii- Create a JS file named <code>user_action.php</code> to handle GET/POST requests</div>
<pre class="crayon-plain-tag">&lt;?php
include_once 'config/Config.php';
include_once 'class/User.php';

$conn = new Config();
$db = $conn-&gt;getConnection();

$user = new User($db);

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'listUsers') {
    $user-&gt;listUsers();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'getUserDetails') {
    $user-&gt;user_id = $_POST[&quot;id&quot;];
    $user-&gt;getUserDetails();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'addUser') {
    $user-&gt;role = $_POST[&quot;role&quot;];
    $user-&gt;first_name = $_POST[&quot;first_name&quot;];
    $user-&gt;last_name = $_POST[&quot;last_name&quot;];
    $user-&gt;email = $_POST[&quot;email&quot;];
    $user-&gt;password = $_POST[&quot;password&quot;];
    $user-&gt;insert();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'updateUser') {
    $user-&gt;id = $_POST[&quot;id&quot;];
    $user-&gt;role = $_POST[&quot;role&quot;];
    $user-&gt;first_name = $_POST[&quot;first_name&quot;];
    $user-&gt;last_name = $_POST[&quot;last_name&quot;];
    $user-&gt;email = $_POST[&quot;email&quot;];
    $user-&gt;password = $_POST[&quot;password&quot;];
    $user-&gt;update();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'deleteUser') {
    $user-&gt;id = $_POST[&quot;id&quot;];
    $user-&gt;delete();
}
?&gt;</pre>

<div class="new-line-label">iv- Create a JS file named <code>user.js</code> to handle Ajax requests, inside the js/ folder</div>
<pre class="crayon-plain-tag">jQuery(document).ready(function () {

    var userRecords = jQuery('#userListing').DataTable({
        &quot;lengthChange&quot;: false,
        &quot;processing&quot;: true,
        &quot;serverSide&quot;: true,
        &quot;bFilter&quot;: false,
        'serverMethod': 'post',
        &quot;order&quot;: [],
        &quot;ajax&quot;: {
            url: &quot;user_action.php&quot;,
            type: &quot;POST&quot;,
            data: { action: 'listUsers' },
            dataType: &quot;json&quot;
        },
        &quot;columnDefs&quot;: [
            {
                &quot;targets&quot;: [0, 4, 5],
                &quot;orderable&quot;: false,
            },
        ],
        &quot;pageLength&quot;: 10
    });

    jQuery('#addUser').click(function () {
        jQuery('#userModal').modal({
            backdrop: 'static',
            keyboard: false
        });
        jQuery(&quot;#userModal&quot;).on(&quot;shown.bs.modal&quot;, function () {
            jQuery('#userForm')[0].reset();
            jQuery('.modal-title').html(&quot;&lt;i class='fa fa-plus'&gt;&lt;/i&gt; Add User&quot;);
            jQuery('#action').val('addUser');
            jQuery('#save').val('Save');
        });
    });

    jQuery(&quot;#userListing&quot;).on('click', '.update', function () {
        var id = jQuery(this).attr(&quot;id&quot;);
        var action = 'getUserDetails';
        jQuery.ajax({
            url: 'user_action.php',
            method: &quot;POST&quot;,
            data: { id: id, action: action },
            dataType: &quot;json&quot;,
            success: function (respData) {
                jQuery(&quot;#userModal&quot;).on(&quot;shown.bs.modal&quot;, function () {
                    jQuery('#userForm')[0].reset();
                    respData.data.forEach(function (item) {
                        jQuery('#id').val(item['id']);
                        jQuery('#role').val(item['role']);
                        jQuery('#first_name').val(item['first_name']);
                        jQuery('#last_name').val(item['last_name']);
                        jQuery('#email').val(item['email']);
                    });
                    jQuery('.modal-title').html(&quot;&lt;i class='fa fa-plus'&gt;&lt;/i&gt; Edit User&quot;);
                    jQuery('#action').val('updateUser');
                    jQuery('#save').val('Save');
                }).modal({
                    backdrop: 'static',
                    keyboard: false
                });
            }
        });
    });

    jQuery(&quot;#userModal&quot;).on('submit', '#userForm', function (event) {
        event.preventDefault();
        jQuery('#save').attr('disabled', 'disabled');
        var formData = jQuery(this).serialize();
        jQuery.ajax({
            url: &quot;user_action.php&quot;,
            method: &quot;POST&quot;,
            data: formData,
            success: function (data) {
                jQuery('#userForm')[0].reset();
                jQuery('#userModal').modal('hide');
                jQuery('#save').attr('disabled', false);
                userRecords.ajax.reload();
            }
        })
    });

    jQuery(&quot;#userListing&quot;).on('click', '.delete', function () {
        var id = jQuery(this).attr(&quot;id&quot;);
        var action = &quot;deleteUser&quot;;
        if (confirm(&quot;Are you sure you want to delete this record?&quot;)) {
            jQuery.ajax({
                url: &quot;user_action.php&quot;,
                method: &quot;POST&quot;,
                data: { id: id, action: action },
                success: function (data) {
                    userRecords.ajax.reload();
                }
            })
        } else {
            return false;
        }
    });

});</pre>

<div class="top-line-bold">Step 3: Manage Books</div>

<div class="new-line-label">i- Create a class file named <code>Books.php</code> inside class/ folder.</div>
<pre class="crayon-plain-tag">&lt;?php

/**
 * Description of Books Class
 *
 * @author Team TechArise
 *
 * @email info@techarise.com
 */

class Books
{

    private $bookTable = 'book';
    private $issuedBookTable = 'issued_book';
    private $categoryTable = 'category';
    private $authorTable = 'author';
    private $publisherTable = 'publisher';
    private $rackTable = 'rack';
    private $conn;

    public function __construct($db)
    {
        $this-&gt;conn = $db;
    }

    public function listBook()
    {

        $sqlQuery = &quot;SELECT book.bookid, book.picture, book.name, book.status, book.isbn, book.no_of_copy, book.updated_on, author.name as author_name, category.name AS category_name, rack.name As rack_name, publisher.name AS publisher_name 
            FROM &quot; . $this-&gt;bookTable . &quot; book          
            LEFT JOIN &quot; . $this-&gt;authorTable . &quot; author ON author.authorid = book.authorid
            LEFT JOIN &quot; . $this-&gt;categoryTable . &quot; category ON category.categoryid = book.categoryid
            LEFT JOIN &quot; . $this-&gt;rackTable . &quot; rack ON rack.rackid = book.rackid
            LEFT JOIN &quot; . $this-&gt;publisherTable . &quot; publisher ON publisher.publisherid = book.publisherid &quot;;

        if (!empty($_POST[&quot;search&quot;][&quot;value&quot;])) {
            $sqlQuery .= ' WHERE (book.bookid LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
            $sqlQuery .= ' OR book.name LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
            $sqlQuery .= ' OR book.status LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
        }

        if (!empty($_POST[&quot;order&quot;])) {
            $sqlQuery .= 'ORDER BY ' . $_POST['order']['0']['column'] . ' ' . $_POST['order']['0']['dir'] . ' ';
        } else {
            $sqlQuery .= 'ORDER BY book.bookid DESC ';
        }

        if ($_POST[&quot;length&quot;] != -1) {
            $sqlQuery .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
        }

        $stmt = $this-&gt;conn-&gt;prepare($sqlQuery);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();

        $stmtTotal = $this-&gt;conn-&gt;prepare($sqlQuery);
        $stmtTotal-&gt;execute();
        $allResult = $stmtTotal-&gt;get_result();
        $allRecords = $allResult-&gt;num_rows;

        $displayRecords = $result-&gt;num_rows;
        $records = array();
        $count = 1;
        while ($book = $result-&gt;fetch_assoc()) {
            $rows = array();
            if (!$book['picture']) {
                $book['picture'] = 'placeholder.png';
            }
            $rows[] = '&lt;img src=&quot;images/' . $book['picture'] . '&quot; width=&quot;50&quot; height=&quot;50&quot;&gt;';
            $rows[] = ucfirst($book['name']);
            $rows[] = ucfirst($book['isbn']);
            $rows[] = ucfirst($book['author_name']);
            $rows[] = ucfirst($book['publisher_name']);
            $rows[] = ucfirst($book['category_name']);
            $rows[] = ucfirst($book['rack_name']);
            $rows[] = ucfirst($book['no_of_copy']);
            $rows[] = $book['status'];
            $rows[] = $book['updated_on'];
            $rows[] = '&lt;button type=&quot;button&quot; name=&quot;update&quot; id=&quot;' . $book[&quot;bookid&quot;] . '&quot; class=&quot;btn btn-primary btn-sm update&quot;&gt;&lt;span class=&quot;fa fa-edit&quot; title=&quot;Edit&quot;&gt; &lt;/span&gt;&lt;/button&gt;&amp;nbsp;&lt;button type=&quot;button&quot; name=&quot;delete&quot; id=&quot;' . $book[&quot;bookid&quot;] . '&quot; class=&quot;btn btn-danger btn-sm delete&quot; &gt;&lt;span class=&quot;fa fa-trash-o&quot; title=&quot;Delete&quot;&gt; &lt;/span&gt;&lt;/button&gt;';
            $records[] = $rows;
            $count++;
        }

        $output = array(
            &quot;draw&quot;  =&gt;  intval($_POST[&quot;draw&quot;]),
            &quot;iTotalRecords&quot; =&gt;  $displayRecords,
            &quot;iTotalDisplayRecords&quot;  =&gt;  $allRecords,
            &quot;data&quot;  =&gt;  $records
        );

        echo json_encode($output);
    }

    public function insert()
    {

        if ($this-&gt;name &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $stmt = $this-&gt;conn-&gt;prepare(&quot;
                INSERT INTO &quot; . $this-&gt;bookTable . &quot;(`name`, `status`, `isbn`, `no_of_copy`, `categoryid`, `authorid`, `rackid`, `publisherid`)
                VALUES(?, ?, ?, ?, ?, ?, ?, ?)&quot;);

            $this-&gt;name = htmlspecialchars(strip_tags($this-&gt;name));
            $this-&gt;isbn = htmlspecialchars(strip_tags($this-&gt;isbn));
            $this-&gt;no_of_copy = htmlspecialchars(strip_tags($this-&gt;no_of_copy));
            $this-&gt;author = htmlspecialchars(strip_tags($this-&gt;author));
            $this-&gt;publisher = htmlspecialchars(strip_tags($this-&gt;publisher));
            $this-&gt;category = htmlspecialchars(strip_tags($this-&gt;category));
            $this-&gt;rack = htmlspecialchars(strip_tags($this-&gt;rack));
            $this-&gt;status = htmlspecialchars(strip_tags($this-&gt;status));

            $stmt-&gt;bind_param(&quot;sssiiiii&quot;, $this-&gt;name, $this-&gt;status, $this-&gt;isbn, $this-&gt;no_of_copy, $this-&gt;category, $this-&gt;author, $this-&gt;rack, $this-&gt;publisher);

            if ($stmt-&gt;execute()) {
                return true;
            }
        }
    }

    public function update()
    {

        if ($this-&gt;name &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $stmt = $this-&gt;conn-&gt;prepare(&quot;
                UPDATE &quot; . $this-&gt;bookTable . &quot; 
                SET name = ?, status = ?, isbn = ?, no_of_copy = ?, categoryid = ?, authorid = ?, rackid = ?, publisherid = ?
                WHERE bookid = ?&quot;);

            $this-&gt;name = htmlspecialchars(strip_tags($this-&gt;name));
            $this-&gt;isbn = htmlspecialchars(strip_tags($this-&gt;isbn));
            $this-&gt;no_of_copy = htmlspecialchars(strip_tags($this-&gt;no_of_copy));
            $this-&gt;author = htmlspecialchars(strip_tags($this-&gt;author));
            $this-&gt;publisher = htmlspecialchars(strip_tags($this-&gt;publisher));
            $this-&gt;category = htmlspecialchars(strip_tags($this-&gt;category));
            $this-&gt;rack = htmlspecialchars(strip_tags($this-&gt;rack));
            $this-&gt;status = htmlspecialchars(strip_tags($this-&gt;status));
            $this-&gt;bookid = htmlspecialchars(strip_tags($this-&gt;bookid));

            $stmt-&gt;bind_param(&quot;sssiiiiii&quot;, $this-&gt;name, $this-&gt;status, $this-&gt;isbn, $this-&gt;no_of_copy, $this-&gt;category, $this-&gt;author, $this-&gt;rack, $this-&gt;publisher, $this-&gt;bookid);

            if ($stmt-&gt;execute()) {
                return true;
            }
        }
    }

    public function delete()
    {
        if ($this-&gt;bookid &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $stmt = $this-&gt;conn-&gt;prepare(&quot;
                DELETE FROM &quot; . $this-&gt;bookTable . &quot; 
                WHERE bookid = ?&quot;);

            $this-&gt;bookid = htmlspecialchars(strip_tags($this-&gt;bookid));

            $stmt-&gt;bind_param(&quot;i&quot;, $this-&gt;bookid);

            if ($stmt-&gt;execute()) {
                return true;
            }
        }
    }

    public function getBookDetails()
    {
        if ($this-&gt;bookid &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $sqlQuery = &quot;SELECT book.bookid, book.picture, book.name, book.status, book.isbn, book.no_of_copy, book.updated_on, author.authorid, category.categoryid, rack.rackid, publisher.publisherid 
            FROM &quot; . $this-&gt;bookTable . &quot; book          
            LEFT JOIN &quot; . $this-&gt;authorTable . &quot; author ON author.authorid = book.authorid
            LEFT JOIN &quot; . $this-&gt;categoryTable . &quot; category ON category.categoryid = book.categoryid
            LEFT JOIN &quot; . $this-&gt;rackTable . &quot; rack ON rack.rackid = book.rackid
            LEFT JOIN &quot; . $this-&gt;publisherTable . &quot; publisher ON publisher.publisherid = book.publisherid 
            WHERE bookid = ? &quot;;

            $stmt = $this-&gt;conn-&gt;prepare($sqlQuery);
            $stmt-&gt;bind_param(&quot;i&quot;, $this-&gt;bookid);
            $stmt-&gt;execute();
            $result = $stmt-&gt;get_result();
            $records = array();
            while ($book = $result-&gt;fetch_assoc()) {
                $rows = array();
                $rows['bookid'] = $book['bookid'];
                $rows['name'] = $book['name'];
                $rows['status'] = $book['status'];
                $rows['isbn'] = $book['isbn'];
                $rows['no_of_copy'] = $book['no_of_copy'];
                $rows['categoryid'] = $book['categoryid'];
                $rows['rackid'] = $book['rackid'];
                $rows['publisherid'] = $book['publisherid'];
                $rows['authorid'] = $book['authorid'];
                $records[] = $rows;
            }
            $output = array(
                &quot;data&quot;  =&gt;  $records
            );
            echo json_encode($output);
        }
    }

    function getAuthorList()
    {
        $stmt = $this-&gt;conn-&gt;prepare(&quot;
        SELECT authorid, name 
        FROM &quot; . $this-&gt;authorTable);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();
        return $result;
    }

    function getCategoryList()
    {
        $stmt = $this-&gt;conn-&gt;prepare(&quot;
        SELECT categoryid, name 
        FROM &quot; . $this-&gt;categoryTable);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();
        return $result;
    }

    function getPublisherList()
    {
        $stmt = $this-&gt;conn-&gt;prepare(&quot;
        SELECT publisherid, name 
        FROM &quot; . $this-&gt;publisherTable);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();
        return $result;
    }

    function getRackList()
    {
        $stmt = $this-&gt;conn-&gt;prepare(&quot;
        SELECT rackid, name 
        FROM &quot; . $this-&gt;rackTable);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();
        return $result;
    }

    function getBookList()
    {
        $stmt = $this-&gt;conn-&gt;prepare(&quot;
        SELECT book.bookid, book.name, issue_book.status
        FROM &quot; . $this-&gt;bookTable . &quot; book
        LEFT JOIN &quot; . $this-&gt;issuedBookTable . &quot; issue_book ON issue_book.bookid = book.bookid&quot;);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();
        return $result;
    }

    function getTotalBooks()
    {
        $stmt = $this-&gt;conn-&gt;prepare(&quot;
        SELECT *
        FROM &quot; . $this-&gt;bookTable);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();
        return $result-&gt;num_rows;
    }


    function getTotalIssuedBooks()
    {
        $stmt = $this-&gt;conn-&gt;prepare(&quot;
        SELECT * 
        FROM &quot; . $this-&gt;issuedBookTable . &quot; 
        WHERE status = 'Issued'&quot;);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();
        return $result-&gt;num_rows;
    }


    function getTotalReturnedBooks()
    {
        $stmt = $this-&gt;conn-&gt;prepare(&quot;
        SELECT * 
        FROM &quot; . $this-&gt;issuedBookTable . &quot; 
        WHERE status = 'Returned'&quot;);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();
        return $result-&gt;num_rows;
    }
}
?&gt;</pre>

<div class="new-line-label">ii- Create HTML file named <code>books.php</code></div>
<pre class="crayon-plain-tag">&lt;?php
include_once 'config/Config.php';
include_once 'class/User.php';
include_once 'class/Books.php';

$conn = new Config();
$db = $conn-&gt;getConnection();

$user = new User($db);

if (!$user-&gt;loggedIn()) {
    header(&quot;Location: index.php&quot;);
}
$book = new Books($db);
include('templates/header.php');
?&gt;


&lt;div class=&quot;container-fluid&quot;&gt;
    &lt;div class=&quot;row&quot;&gt;
        &lt;?php include('templates/left_menus.php'); ?&gt;
        &lt;div class=&quot;col-md-10 col-lg-10&quot;&gt;
            &lt;h2&gt;Manage Books&lt;/h2&gt;
            &lt;div class=&quot;panel-heading&quot;&gt;
                &lt;div class=&quot;row&quot;&gt;
                    &lt;div class=&quot;col-md-10&quot;&gt;
                        &lt;h3 class=&quot;panel-title&quot;&gt;&lt;/h3&gt;
                    &lt;/div&gt;
                    &lt;div class=&quot;col-md-2&quot; align=&quot;right&quot;&gt;
                        &lt;button type=&quot;button&quot; id=&quot;addBook&quot; class=&quot;btn btn-info btn-sm&quot; title=&quot;Add book&quot;&gt;&lt;span class=&quot;fa fa-plus&quot;&gt; Add Book&lt;/span&gt;&lt;/button&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
            &lt;table id=&quot;bookListing&quot; class=&quot;table table-striped table-bordered&quot;&gt;
                &lt;thead&gt;
                    &lt;tr&gt;
                        &lt;td style=&quot;width: 5%;&quot;&gt;#&lt;/td&gt;
                        &lt;th style=&quot;width: 10%;&quot;&gt;Book&lt;/th&gt;
                        &lt;th style=&quot;width: 10%;&quot;&gt;ISBN&lt;/th&gt;
                        &lt;th style=&quot;width: 10%;&quot;&gt;Author&lt;/th&gt;
                        &lt;th style=&quot;width: 10%;&quot;&gt;Publisher&lt;/th&gt;
                        &lt;th style=&quot;width: 10%;&quot;&gt;Category&lt;/th&gt;
                        &lt;th style=&quot;width: 8%;&quot;&gt;Rack&lt;/th&gt;
                        &lt;th style=&quot;width: 10%;&quot;&gt;No of copy&lt;/th&gt;
                        &lt;th style=&quot;width: 5%;&quot;&gt;Status&lt;/th&gt;
                        &lt;th style=&quot;width: 10%;&quot;&gt;Updated On&lt;/th&gt;
                        &lt;th style=&quot;width: 12%;&quot;&gt;Action&lt;/th&gt;
                    &lt;/tr&gt;
                &lt;/thead&gt;
            &lt;/table&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;?php
include('popup/add-book.php');
include('templates/footer.php');
?&gt;</pre>

<div class="new-line-label">iii- Create a JS file named <code>books_action.php</code> to handle GET/POST requests</div>
<pre class="crayon-plain-tag">&lt;?php
include_once 'config/Config.php';
include_once 'class/Books.php';

$conn = new Config();
$db = $conn-&gt;getConnection();

$book = new Books($db);

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'listBook') {
    $book-&gt;listBook();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'getBookDetails') {
    $book-&gt;bookid = $_POST[&quot;bookid&quot;];
    $book-&gt;getBookDetails();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'addBook') {
    $book-&gt;name = $_POST[&quot;name&quot;];
    $book-&gt;isbn = $_POST[&quot;isbn&quot;];
    $book-&gt;no_of_copy = $_POST[&quot;no_of_copy&quot;];
    $book-&gt;author = $_POST[&quot;author&quot;];
    $book-&gt;publisher = $_POST[&quot;publisher&quot;];
    $book-&gt;category = $_POST[&quot;category&quot;];
    $book-&gt;rack = $_POST[&quot;rack&quot;];
    $book-&gt;status = $_POST[&quot;status&quot;];   
    $book-&gt;insert();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'updateBook') {
    $book-&gt;bookid = $_POST[&quot;bookid&quot;];
    $book-&gt;name = $_POST[&quot;name&quot;];
    $book-&gt;isbn = $_POST[&quot;isbn&quot;];
    $book-&gt;no_of_copy = $_POST[&quot;no_of_copy&quot;];
    $book-&gt;author = $_POST[&quot;author&quot;];
    $book-&gt;publisher = $_POST[&quot;publisher&quot;];
    $book-&gt;category = $_POST[&quot;category&quot;];
    $book-&gt;rack = $_POST[&quot;rack&quot;];
    $book-&gt;status = $_POST[&quot;status&quot;];
    $book-&gt;update();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'deleteBook') {
    $book-&gt;bookid = $_POST[&quot;bookid&quot;];
    $book-&gt;delete();
}
?&gt;</pre>

<div class="new-line-label">iv- Create a JS file named <code>books.js</code> to handle Ajax requests, inside the js/ folder</div>
<pre class="crayon-plain-tag">jQuery(document).ready(function () {

    var bookRecords = jQuery('#bookListing').DataTable({
        &quot;lengthChange&quot;: false,
        &quot;processing&quot;: true,
        &quot;serverSide&quot;: true,
        &quot;bFilter&quot;: false,
        'serverMethod': 'post',
        &quot;order&quot;: [],
        &quot;ajax&quot;: {
            url: &quot;books_action.php&quot;,
            type: &quot;POST&quot;,
            data: { action: 'listBook' },
            dataType: &quot;json&quot;
        },
        &quot;columnDefs&quot;: [
            {
                &quot;targets&quot;: [0, 9, 10],
                &quot;orderable&quot;: false,
            },
        ],
        &quot;pageLength&quot;: 10
    });

    jQuery('#addBook').click(function () {
        jQuery('#bookModal').modal({
            backdrop: 'static',
            keyboard: false
        });
        jQuery(&quot;#bookModal&quot;).on(&quot;shown.bs.modal&quot;, function () {
            jQuery('#bookForm')[0].reset();
            jQuery('.modal-title').html(&quot;&lt;i class='fa fa-plus'&gt;&lt;/i&gt; Add Book&quot;);
            jQuery('#action').val('addBook');
            jQuery('#save').val('Save');
        });
    });

    jQuery(&quot;#bookListing&quot;).on('click', '.update', function () {
        var bookid = jQuery(this).attr(&quot;id&quot;);
        var action = 'getBookDetails';
        jQuery.ajax({
            url: 'books_action.php',
            method: &quot;POST&quot;,
            data: { bookid: bookid, action: action },
            dataType: &quot;json&quot;,
            success: function (respData) {
                jQuery(&quot;#bookModal&quot;).on(&quot;shown.bs.modal&quot;, function () {
                    jQuery('#bookForm')[0].reset();
                    respData.data.forEach(function (item) {
                        jQuery('#bookid').val(item['bookid']);
                        jQuery('#name').val(item['name']);
                        jQuery('#isbn').val(item['isbn']);
                        jQuery('#no_of_copy').val(item['no_of_copy']);
                        jQuery('#category').val(item['categoryid']);
                        jQuery('#rack').val(item['rackid']);
                        jQuery('#publisher').val(item['publisherid']);
                        jQuery('#author').val(item['authorid']);
                        jQuery('#status').val(item['status']);
                    });
                    jQuery('.modal-title').html(&quot;&lt;i class='fa fa-plus'&gt;&lt;/i&gt; Edit Book&quot;);
                    jQuery('#action').val('updateBook');
                    jQuery('#save').val('Save');
                }).modal({
                    backdrop: 'static',
                    keyboard: false
                });
            }
        });
    });

    jQuery(&quot;#bookModal&quot;).on('submit', '#bookForm', function (event) {
        event.preventDefault();
        jQuery('#save').attr('disabled', 'disabled');
        var formData = jQuery(this).serialize();
        jQuery.ajax({
            url: &quot;books_action.php&quot;,
            method: &quot;POST&quot;,
            data: formData,
            success: function (data) {
                jQuery('#bookForm')[0].reset();
                jQuery('#bookModal').modal('hide');
                jQuery('#save').attr('disabled', false);
                bookRecords.ajax.reload();
            }
        })
    });

    jQuery(&quot;#bookListing&quot;).on('click', '.delete', function () {
        var bookid = jQuery(this).attr(&quot;id&quot;);
        var action = &quot;deleteBook&quot;;
        if (confirm(&quot;Are you sure you want to delete this record?&quot;)) {
            jQuery.ajax({
                url: &quot;books_action.php&quot;,
                method: &quot;POST&quot;,
                data: { bookid: bookid, action: action },
                success: function (data) {
                    bookRecords.ajax.reload();
                }
            })
        } else {
            return false;
        }
    });

});</pre>

<div class="top-line-bold">Step 4: Manage Issued Books</div>

<div class="new-line-label">i- Create a class file named <code>IssueBooks.php</code> inside class/ folder.</div>
<pre class="crayon-plain-tag">&lt;?php

/**
 * Description of IssueBooks Class
 *
 * @author Team TechArise
 *
 * @email info@techarise.com
 */

class IssueBooks
{

    private $issuedBookTable = 'issued_book';
    private $bookTable = 'book';
    private $userTable = 'user';
    private $conn;

    public function __construct($db)
    {
        $this-&gt;conn = $db;
    }

    public function listIssuedBook()
    {

        $sqlQuery = &quot;SELECT issue_book.issuebookid, issue_book.issue_date_time, issue_book.expected_return_date, issue_book.return_date_time, issue_book.status, book.name As book_name, book.isbn, user.first_name, user.last_name 
            FROM &quot; . $this-&gt;issuedBookTable . &quot; issue_book          
            LEFT JOIN &quot; . $this-&gt;bookTable . &quot; book ON book.bookid = issue_book.bookid
            LEFT JOIN &quot; . $this-&gt;userTable . &quot; user ON user.id = issue_book.userid &quot;;

        if (!empty($_POST[&quot;search&quot;][&quot;value&quot;])) {
            $sqlQuery .= ' WHERE (issue_book.issuebookid LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
            $sqlQuery .= ' OR issue_book.issue_date_time LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
            $sqlQuery .= ' OR issue_book.status LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
        }

        if (!empty($_POST[&quot;order&quot;])) {
            $sqlQuery .= 'ORDER BY ' . $_POST['order']['0']['column'] . ' ' . $_POST['order']['0']['dir'] . ' ';
        } else {
            $sqlQuery .= 'ORDER BY issue_book.issuebookid DESC ';
        }

        if ($_POST[&quot;length&quot;] != -1) {
            $sqlQuery .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
        }

        $stmt = $this-&gt;conn-&gt;prepare($sqlQuery);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();

        $stmtTotal = $this-&gt;conn-&gt;prepare($sqlQuery);
        $stmtTotal-&gt;execute();
        $allResult = $stmtTotal-&gt;get_result();
        $allRecords = $allResult-&gt;num_rows;

        $displayRecords = $result-&gt;num_rows;
        $records = array();
        $count = 1;
        while ($issueBook = $result-&gt;fetch_assoc()) {
            $rows = array();
            $rows[] = $count;
            $rows[] = ucfirst($issueBook['book_name']);
            $rows[] = ucfirst($issueBook['isbn']);
            $rows[] = ucfirst($issueBook['first_name']) . &quot; &quot; . ucfirst($issueBook['last_name']);
            $rows[] = ucfirst($issueBook['issue_date_time']);
            $rows[] = ucfirst($issueBook['expected_return_date']);
            $rows[] = ucfirst($issueBook['return_date_time']);
            $rows[] = $issueBook['status'];
            $rows[] = '&lt;button type=&quot;button&quot; name=&quot;update&quot; id=&quot;' . $issueBook[&quot;issuebookid&quot;] . '&quot; class=&quot;btn btn-primary btn-sm update&quot;&gt;&lt;span class=&quot;fa fa-edit&quot; title=&quot;Edit&quot;&gt; Edit&lt;/span&gt;&lt;/button&gt;';
            $rows[] = '&lt;button type=&quot;button&quot; name=&quot;delete&quot; id=&quot;' . $issueBook[&quot;issuebookid&quot;] . '&quot; class=&quot;btn btn-danger btn-sm delete&quot; &gt;&lt;span class=&quot;fa fa-trash-o&quot; title=&quot;Delete&quot;&gt; Delete&lt;/span&gt;&lt;/button&gt;';
            $records[] = $rows;
            $count++;
        }

        $output = array(
            &quot;draw&quot;  =&gt;  intval($_POST[&quot;draw&quot;]),
            &quot;iTotalRecords&quot; =&gt;  $displayRecords,
            &quot;iTotalDisplayRecords&quot;  =&gt;  $allRecords,
            &quot;data&quot;  =&gt;  $records
        );

        echo json_encode($output);
    }

    public function insert()
    {

        if ($this-&gt;book &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $stmt = $this-&gt;conn-&gt;prepare(&quot;
                INSERT INTO &quot; . $this-&gt;issuedBookTable . &quot;(`bookid`, `userid`, `expected_return_date`, `return_date_time`, `status`)
                VALUES(?, ?, ?, ?, ?)&quot;);

            $this-&gt;book = htmlspecialchars(strip_tags($this-&gt;book));
            $this-&gt;users = htmlspecialchars(strip_tags($this-&gt;users));
            $this-&gt;expected_return_date = htmlspecialchars(strip_tags($this-&gt;expected_return_date));
            $this-&gt;return_date = htmlspecialchars(strip_tags($this-&gt;return_date));
            $this-&gt;status = htmlspecialchars(strip_tags($this-&gt;status));

            $stmt-&gt;bind_param(&quot;iisss&quot;, $this-&gt;book, $this-&gt;users, $this-&gt;expected_return_date, $this-&gt;return_date, $this-&gt;status);

            if ($stmt-&gt;execute()) {
                return true;
            }
        }
    }

    public function update()
    {

        if ($this-&gt;issuebookid &amp;&amp; $this-&gt;book &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $stmt = $this-&gt;conn-&gt;prepare(&quot;
                UPDATE &quot; . $this-&gt;issuedBookTable . &quot; 
                SET bookid = ?, userid = ?, expected_return_date = ?, return_date_time = ?, status = ?
                WHERE issuebookid = ?&quot;);

            $this-&gt;book = htmlspecialchars(strip_tags($this-&gt;book));
            $this-&gt;users = htmlspecialchars(strip_tags($this-&gt;users));
            $this-&gt;expected_return_date = htmlspecialchars(strip_tags($this-&gt;expected_return_date));
            $this-&gt;return_date = htmlspecialchars(strip_tags($this-&gt;return_date));
            $this-&gt;status = htmlspecialchars(strip_tags($this-&gt;status));

            $stmt-&gt;bind_param(&quot;iisssi&quot;, $this-&gt;book, $this-&gt;users, $this-&gt;expected_return_date, $this-&gt;return_date, $this-&gt;status, $this-&gt;issuebookid);

            if ($stmt-&gt;execute()) {
                return true;
            }
        }
    }

    public function delete()
    {
        if ($this-&gt;issuebookid &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $stmt = $this-&gt;conn-&gt;prepare(&quot;
                DELETE FROM &quot; . $this-&gt;issuedBookTable . &quot; 
                WHERE issuebookid = ?&quot;);

            $this-&gt;issuebookid = htmlspecialchars(strip_tags($this-&gt;issuebookid));

            $stmt-&gt;bind_param(&quot;i&quot;, $this-&gt;issuebookid);

            if ($stmt-&gt;execute()) {
                return true;
            }
        }
    }

    public function getIssueBookDetails()
    {
        if ($this-&gt;issuebookid &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $sqlQuery = &quot;SELECT issue_book.issuebookid, issue_book.issue_date_time, issue_book.expected_return_date, issue_book.return_date_time, issue_book.status, issue_book.bookid, issue_book.userid, book.name AS book_name
            FROM &quot; . $this-&gt;issuedBookTable . &quot; issue_book          
            LEFT JOIN &quot; . $this-&gt;bookTable . &quot; book ON book.bookid = issue_book.bookid
            LEFT JOIN &quot; . $this-&gt;userTable . &quot; user ON user.id = issue_book.userid
            WHERE issue_book.issuebookid = ?&quot;;

            $stmt = $this-&gt;conn-&gt;prepare($sqlQuery);
            $stmt-&gt;bind_param(&quot;i&quot;, $this-&gt;issuebookid);
            $stmt-&gt;execute();
            $result = $stmt-&gt;get_result();
            $records = array();
            while ($issueBook = $result-&gt;fetch_assoc()) {
                $rows = array();
                $rows['issuebookid'] = $issueBook['issuebookid'];
                $rows['bookid'] = $issueBook['bookid'];
                $rows['book_name'] = $issueBook['book_name'];
                $rows['status'] = $issueBook['status'];
                $rows['userid'] = $issueBook['userid'];
                $rows['expected_return_date'] = date('Y-m-d\TH:i:s', strtotime($issueBook['expected_return_date']));
                $rows['return_date_time'] = date('Y-m-d\TH:i:s', strtotime($issueBook['return_date_time']));
                $records[] = $rows;
            }
            $output = array(
                &quot;data&quot;  =&gt;  $records
            );
            echo json_encode($output);
        }
    }
}
?&gt;</pre>

<div class="new-line-label">ii- Create HTML file named <code>issue_books.php</code></div>
<pre class="crayon-plain-tag">&lt;?php
include_once 'config/Config.php';
include_once 'class/User.php';
include_once 'class/Books.php';

$conn = new Config();
$db = $conn-&gt;getConnection();

$user = new User($db);

if (!$user-&gt;loggedIn()) {
    header(&quot;Location: index.php&quot;);
}
$book = new Books($db);
include('templates/header.php');
?&gt;

&lt;div class=&quot;container-fluid&quot;&gt;
    &lt;div class=&quot;row&quot;&gt;
        &lt;?php include('templates/left_menus.php'); ?&gt;
        &lt;div class=&quot;col-md-10 col-lg-10&quot;&gt;
            &lt;h2&gt;Manage Issue Books&lt;/h2&gt;
            &lt;div class=&quot;panel-heading&quot;&gt;
                &lt;div class=&quot;row&quot;&gt;
                    &lt;div class=&quot;col-md-10&quot;&gt;
                        &lt;h3 class=&quot;panel-title&quot;&gt;&lt;/h3&gt;
                    &lt;/div&gt;
                    &lt;div class=&quot;col-md-2&quot; align=&quot;right&quot;&gt;
                        &lt;button type=&quot;button&quot; id=&quot;issueBook&quot; class=&quot;btn btn-info btn-sm&quot; title=&quot;Issue Book&quot;&gt;&lt;span class=&quot;fa fa-plus&quot;&gt; Issue Book&lt;/span&gt;&lt;/button&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
            &lt;table id=&quot;issuedBookListing&quot; class=&quot;table table-striped table-bordered&quot;&gt;
                &lt;thead&gt;
                    &lt;tr&gt;
                        &lt;th&gt;Id&lt;/th&gt;
                        &lt;th&gt;Book&lt;/th&gt;
                        &lt;th&gt;ISBN&lt;/th&gt;
                        &lt;th&gt;User&lt;/th&gt;
                        &lt;th&gt;Issue Date&lt;/th&gt;
                        &lt;th&gt;Expected Return&lt;/th&gt;
                        &lt;th&gt;Return Date&lt;/th&gt;
                        &lt;th&gt;Status&lt;/th&gt;
                        &lt;th&gt;&lt;/th&gt;
                        &lt;th&gt;&lt;/th&gt;
                    &lt;/tr&gt;
                &lt;/thead&gt;
            &lt;/table&gt;
        &lt;/div&gt;
    &lt;/div&gt;  
&lt;/div&gt;
&lt;?php
include('popup/add-issue-books.php');
include('templates/footer.php');
?&gt;</pre>

<div class="new-line-label">iii- Create a JS file named <code>issue_books_action.php</code> to handle GET/POST requests</div>
<pre class="crayon-plain-tag">&lt;?php
include_once 'config/Config.php';
include_once 'class/IssueBooks.php';

$conn = new Config();
$db = $conn-&gt;getConnection();

$issueBook = new IssueBooks($db);

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'listIssuedBook') {
    $issueBook-&gt;listIssuedBook();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'getIssueBookDetails') {
    $issueBook-&gt;issuebookid = $_POST[&quot;issuebookid&quot;];
    $issueBook-&gt;getIssueBookDetails();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'issueBook') {
    $issueBook-&gt;book = $_POST[&quot;book&quot;];
    $issueBook-&gt;users = $_POST[&quot;users&quot;];
    $issueBook-&gt;expected_return_date = $_POST[&quot;expected_return_date&quot;];
    $issueBook-&gt;return_date = $_POST[&quot;return_date&quot;];
    $issueBook-&gt;status = $_POST[&quot;status&quot;];  
    $issueBook-&gt;insert();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'updateIssueBook') {
    $issueBook-&gt;issuebookid = $_POST[&quot;issuebookid&quot;];
    $issueBook-&gt;book = $_POST[&quot;book&quot;];
    $issueBook-&gt;users = $_POST[&quot;users&quot;];
    $issueBook-&gt;expected_return_date = $_POST[&quot;expected_return_date&quot;];
    $issueBook-&gt;return_date = $_POST[&quot;return_date&quot;];
    $issueBook-&gt;status = $_POST[&quot;status&quot;];  
    $issueBook-&gt;update();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'deleteIssueBook') {
    $issueBook-&gt;issuebookid = $_POST[&quot;issuebookid&quot;];
    $issueBook-&gt;delete();
}
?&gt;</pre>

<div class="new-line-label">iv- Create a JS file named <code>issue_books.js</code> to handle Ajax requests, inside the js/ folder</div>
<pre class="crayon-plain-tag">jQuery(document).ready(function () {

    var issuedBookRecords = jQuery('#issuedBookListing').DataTable({
        &quot;lengthChange&quot;: false,
        &quot;processing&quot;: true,
        &quot;serverSide&quot;: true,
        &quot;bFilter&quot;: false,
        'serverMethod': 'post',
        &quot;order&quot;: [],
        &quot;ajax&quot;: {
            url: &quot;issue_books_action.php&quot;,
            type: &quot;POST&quot;,
            data: { action: 'listIssuedBook' },
            dataType: &quot;json&quot;
        },
        &quot;columnDefs&quot;: [
            {
                &quot;targets&quot;: [0, 8, 9],
                &quot;orderable&quot;: false,
            },
        ],
        &quot;pageLength&quot;: 10
    });

    jQuery('#issueBook').click(function () {
        jQuery('#issuedBookModal').modal({
            backdrop: 'static',
            keyboard: false
        });
        jQuery(&quot;#issuedBookModal&quot;).on(&quot;shown.bs.modal&quot;, function () {
            jQuery('#issuedBookForm')[0].reset();
            jQuery('.modal-title').html(&quot;&lt;i class='fa fa-plus'&gt;&lt;/i&gt; Issue Book&quot;);
            jQuery('#action').val('issueBook');
            jQuery('#save').val('Save');
        });
    });

    jQuery(&quot;#issuedBookListing&quot;).on('click', '.update', function () {
        var issuebookid = jQuery(this).attr(&quot;id&quot;);
        var action = 'getIssueBookDetails';
        jQuery.ajax({
            url: 'issue_books_action.php',
            method: &quot;POST&quot;,
            data: { issuebookid: issuebookid, action: action },
            dataType: &quot;json&quot;,
            success: function (respData) {
                jQuery(&quot;#issuedBookModal&quot;).on(&quot;shown.bs.modal&quot;, function () {
                    jQuery('#issuedBookForm')[0].reset();
                    respData.data.forEach(function (item) {
                        jQuery('#issuebookid').val(item['issuebookid']);
                        jQuery('#book').val(item['bookid']);
                        jQuery('#users').val(item['userid']);
                        jQuery('#expected_return_date').val(item['expected_return_date']);
                        jQuery('#return_date').val(item['return_date_time']);
                        jQuery('#status').val(item['status']);
                    });
                    jQuery('.modal-title').html(&quot;&lt;i class='fa fa-plus'&gt;&lt;/i&gt; Edit issued Book&quot;);
                    jQuery('#action').val('updateIssueBook');
                    jQuery('#save').val('Save');
                }).modal({
                    backdrop: 'static',
                    keyboard: false
                });
            }
        });
    });

    jQuery(&quot;#issuedBookModal&quot;).on('submit', '#issuedBookForm', function (event) {
        event.preventDefault();
        jQuery('#save').attr('disabled', 'disabled');
        var formData = jQuery(this).serialize();
        jQuery.ajax({
            url: &quot;issue_books_action.php&quot;,
            method: &quot;POST&quot;,
            data: formData,
            success: function (data) {
                jQuery('#issuedBookForm')[0].reset();
                jQuery('#issuedBookModal').modal('hide');
                jQuery('#save').attr('disabled', false);
                issuedBookRecords.ajax.reload();
            }
        })
    });

    jQuery(&quot;#issuedBookListing&quot;).on('click', '.delete', function () {
        var issuebookid = jQuery(this).attr(&quot;id&quot;);
        var action = &quot;deleteIssueBook&quot;;
        if (confirm(&quot;Are you sure you want to delete this record?&quot;)) {
            jQuery.ajax({
                url: &quot;issue_books_action.php&quot;,
                method: &quot;POST&quot;,
                data: { issuebookid: issuebookid, action: action },
                success: function (data) {
                    issuedBookRecords.ajax.reload();
                }
            })
        } else {
            return false;
        }
    });

});</pre>

<div class="top-line-bold">Step 5: Manage Book Rack</div>

<div class="new-line-label">i- Create a class file named <code>Rack.php</code> inside class/ folder.</div>
<pre class="crayon-plain-tag">&lt;?php

/**
 * Description of Rack Class
 *
 * @author Team TechArise
 *
 * @email info@techarise.com
 */

class Rack
{

    private $rackTable = 'rack';
    private $conn;

    public function __construct($db)
    {
        $this-&gt;conn = $db;
    }

    public function listRack()
    {

        $sqlQuery = &quot;SELECT rackid, name, status
            FROM &quot; . $this-&gt;rackTable . &quot; &quot;;

        if (!empty($_POST[&quot;search&quot;][&quot;value&quot;])) {
            $sqlQuery .= ' WHERE (rackid LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
            $sqlQuery .= ' OR name LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
            $sqlQuery .= ' OR status LIKE &quot;%' . $_POST[&quot;search&quot;][&quot;value&quot;] . '%&quot; ';
        }

        if (!empty($_POST[&quot;order&quot;])) {
            $sqlQuery .= 'ORDER BY ' . $_POST['order']['0']['column'] . ' ' . $_POST['order']['0']['dir'] . ' ';
        } else {
            $sqlQuery .= 'ORDER BY rackid DESC ';
        }

        if ($_POST[&quot;length&quot;] != -1) {
            $sqlQuery .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
        }

        $stmt = $this-&gt;conn-&gt;prepare($sqlQuery);
        $stmt-&gt;execute();
        $result = $stmt-&gt;get_result();

        $stmtTotal = $this-&gt;conn-&gt;prepare($sqlQuery);
        $stmtTotal-&gt;execute();
        $allResult = $stmtTotal-&gt;get_result();
        $allRecords = $allResult-&gt;num_rows;

        $displayRecords = $result-&gt;num_rows;
        $records = array();
        $count = 1;
        while ($rack = $result-&gt;fetch_assoc()) {
            $rows = array();
            $rows[] = $count;
            $rows[] = ucfirst($rack['name']);
            $rows[] = $rack['status'];
            $rows[] = '&lt;button type=&quot;button&quot; name=&quot;update&quot; id=&quot;' . $rack[&quot;rackid&quot;] . '&quot; class=&quot;btn btn-primary btn-sm update&quot;&gt;&lt;span class=&quot;fa fa-edit&quot; title=&quot;Edit&quot;&gt; Edit&lt;/span&gt;&lt;/button&gt;';
            $rows[] = '&lt;button type=&quot;button&quot; name=&quot;delete&quot; id=&quot;' . $rack[&quot;rackid&quot;] . '&quot; class=&quot;btn btn-danger btn-sm delete&quot; &gt;&lt;span class=&quot;fa fa-trash-o&quot; title=&quot;Delete&quot;&gt; Delete&lt;/span&gt;&lt;/button&gt;';
            $records[] = $rows;
            $count++;
        }

        $output = array(
            &quot;draw&quot;  =&gt;  intval($_POST[&quot;draw&quot;]),
            &quot;iTotalRecords&quot; =&gt;  $displayRecords,
            &quot;iTotalDisplayRecords&quot;  =&gt;  $allRecords,
            &quot;data&quot;  =&gt;  $records
        );

        echo json_encode($output);
    }

    public function insert()
    {

        if ($this-&gt;name &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $stmt = $this-&gt;conn-&gt;prepare(&quot;
                INSERT INTO &quot; . $this-&gt;rackTable . &quot;(`name`, `status`)
                VALUES(?, ?)&quot;);

            $this-&gt;name = htmlspecialchars(strip_tags($this-&gt;name));
            $this-&gt;status = htmlspecialchars(strip_tags($this-&gt;status));

            $stmt-&gt;bind_param(&quot;ss&quot;, $this-&gt;name, $this-&gt;status);

            if ($stmt-&gt;execute()) {
                return true;
            }
        }
    }

    public function update()
    {

        if ($this-&gt;name &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $stmt = $this-&gt;conn-&gt;prepare(&quot;
                UPDATE &quot; . $this-&gt;rackTable . &quot; 
                SET name = ?, status = ?
                WHERE rackid = ?&quot;);

            $this-&gt;name = htmlspecialchars(strip_tags($this-&gt;name));
            $this-&gt;status = htmlspecialchars(strip_tags($this-&gt;status));
            $this-&gt;rackid = htmlspecialchars(strip_tags($this-&gt;rackid));

            $stmt-&gt;bind_param(&quot;ssi&quot;, $this-&gt;name, $this-&gt;status, $this-&gt;rackid);

            if ($stmt-&gt;execute()) {
                return true;
            }
        }
    }

    public function delete()
    {
        if ($this-&gt;rackid &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $stmt = $this-&gt;conn-&gt;prepare(&quot;
                DELETE FROM &quot; . $this-&gt;rackTable . &quot; 
                WHERE rackid = ?&quot;);

            $this-&gt;rackid = htmlspecialchars(strip_tags($this-&gt;rackid));

            $stmt-&gt;bind_param(&quot;i&quot;, $this-&gt;rackid);

            if ($stmt-&gt;execute()) {
                return true;
            }
        }
    }

    public function getRackDetails()
    {
        if ($this-&gt;rackid &amp;&amp; $_SESSION[&quot;userid&quot;]) {

            $sqlQuery = &quot;
                SELECT rackid, name, status
                FROM &quot; . $this-&gt;rackTable . &quot;           
                WHERE rackid = ? &quot;;

            $stmt = $this-&gt;conn-&gt;prepare($sqlQuery);
            $stmt-&gt;bind_param(&quot;i&quot;, $this-&gt;rackid);
            $stmt-&gt;execute();
            $result = $stmt-&gt;get_result();
            $records = array();
            while ($rack = $result-&gt;fetch_assoc()) {
                $rows = array();
                $rows['rackid'] = $rack['rackid'];
                $rows['name'] = $rack['name'];
                $rows['status'] = $rack['status'];
                $records[] = $rows;
            }
            $output = array(
                &quot;data&quot;  =&gt;  $records
            );
            echo json_encode($output);
        }
    }
}
?&gt;</pre>

<div class="new-line-label">ii- Create HTML file named <code>rack.php</code></div>
<pre class="crayon-plain-tag">&lt;?php
include_once 'config/Config.php';
include_once 'class/User.php';

$conn = new Config();
$db = $conn-&gt;getConnection();

$user = new User($db);

if (!$user-&gt;loggedIn()) {
    header(&quot;Location: index.php&quot;);
}
include('templates/header.php');
?&gt;

&lt;div class=&quot;container-fluid&quot;&gt;
    &lt;div class=&quot;row&quot;&gt;
        &lt;?php include('templates/left_menus.php'); ?&gt;
        &lt;div class=&quot;col-md-10 col-lg-10&quot;&gt;
            &lt;h2&gt;Rack Location List&lt;/h2&gt;
            &lt;div class=&quot;panel-heading&quot;&gt;
                &lt;div class=&quot;row&quot;&gt;
                    &lt;div class=&quot;col-md-10&quot;&gt;
                        &lt;h3 class=&quot;panel-title&quot;&gt;&lt;/h3&gt;
                    &lt;/div&gt;
                    &lt;div class=&quot;col-md-2&quot; align=&quot;right&quot;&gt;
                        &lt;button type=&quot;button&quot; id=&quot;addRack&quot; class=&quot;btn btn-info btn-sm&quot; title=&quot;Add Rack&quot;&gt;&lt;span class=&quot;fa fa-plus&quot;&gt; Add&lt;/span&gt;&lt;/button&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
            &lt;table id=&quot;rackListing&quot; class=&quot;table table-striped table-bordered&quot;&gt;
                &lt;thead&gt;
                    &lt;tr&gt;
                        &lt;th&gt;Sn.&lt;/th&gt;
                        &lt;th&gt;Name&lt;/th&gt;
                        &lt;th&gt;Status&lt;/th&gt;
                        &lt;th&gt;&lt;/th&gt;
                        &lt;th&gt;&lt;/th&gt;
                    &lt;/tr&gt;
                &lt;/thead&gt;
            &lt;/table&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;?php
include('popup/add-rack.php');
include('templates/footer.php');
?&gt;</pre>

<div class="new-line-label">iii- Create a JS file named <code>rack_action.php</code> to handle GET/POST requests</div>
<pre class="crayon-plain-tag">&lt;?php
include_once 'config/Config.php';
include_once 'class/Rack.php';

$conn = new Config();
$db = $conn-&gt;getConnection();

$rack = new Rack($db);

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'listRack') {
    $rack-&gt;listRack();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'getRackDetails') {
    $rack-&gt;rackid = $_POST[&quot;rackid&quot;];
    $rack-&gt;getRackDetails();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'addRack') {
    $rack-&gt;name = $_POST[&quot;name&quot;];
    $rack-&gt;status = $_POST[&quot;status&quot;];   
    $rack-&gt;insert();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'updateRack') {
    $rack-&gt;rackid = $_POST[&quot;rackid&quot;];
    $rack-&gt;name = $_POST[&quot;name&quot;];
    $rack-&gt;status = $_POST[&quot;status&quot;];
    $rack-&gt;update();
}

if(!empty($_POST['action']) &amp;&amp; $_POST['action'] == 'deleteRack') {
    $rack-&gt;rackid = $_POST[&quot;rackid&quot;];
    $rack-&gt;delete();
}
?&gt;</pre>

<div class="new-line-label">iv- Create a JS file named <code>rack.js</code> to handle Ajax requests, inside the js/ folder</div>
<pre class="crayon-plain-tag">jQuery(document).ready(function () {

    var rackRecords = jQuery('#rackListing').DataTable({
        &quot;lengthChange&quot;: false,
        &quot;processing&quot;: true,
        &quot;serverSide&quot;: true,
        &quot;bFilter&quot;: false,
        'serverMethod': 'post',
        &quot;order&quot;: [],
        &quot;ajax&quot;: {
            url: &quot;rack_action.php&quot;,
            type: &quot;POST&quot;,
            data: { action: 'listRack' },
            dataType: &quot;json&quot;
        },
        &quot;columnDefs&quot;: [
            {
                &quot;targets&quot;: [0, 3, 4],
                &quot;orderable&quot;: false,
            },
        ],
        &quot;pageLength&quot;: 10
    });

    jQuery('#addRack').click(function () {
        jQuery('#rackModal').modal({
            backdrop: 'static',
            keyboard: false
        });
        jQuery(&quot;#rackModal&quot;).on(&quot;shown.bs.modal&quot;, function () {
            jQuery('#rackForm')[0].reset();
            jQuery('.modal-title').html(&quot;&lt;i class='fa fa-plus'&gt;&lt;/i&gt; Add Rack&quot;);
            jQuery('#action').val('addRack');
            jQuery('#save').val('Save');
        });
    });

    jQuery(&quot;#rackListing&quot;).on('click', '.update', function () {
        var rackid = jQuery(this).attr(&quot;id&quot;);
        var action = 'getRackDetails';
        jQuery.ajax({
            url: 'rack_action.php',
            method: &quot;POST&quot;,
            data: { rackid: rackid, action: action },
            dataType: &quot;json&quot;,
            success: function (respData) {
                jQuery(&quot;#rackModal&quot;).on(&quot;shown.bs.modal&quot;, function () {
                    jQuery('#rackForm')[0].reset();
                    respData.data.forEach(function (item) {
                        jQuery('#rackid').val(item['rackid']);
                        jQuery('#name').val(item['name']);
                        jQuery('#status').val(item['status']);
                    });
                    jQuery('.modal-title').html(&quot;&lt;i class='fa fa-plus'&gt;&lt;/i&gt; Edit Rack&quot;);
                    jQuery('#action').val('updateRack');
                    jQuery('#save').val('Save');
                }).modal({
                    backdrop: 'static',
                    keyboard: false
                });
            }
        });
    });

    jQuery(&quot;#rackModal&quot;).on('submit', '#rackForm', function (event) {
        event.preventDefault();
        jQuery('#save').attr('disabled', 'disabled');
        var formData = jQuery(this).serialize();
        jQuery.ajax({
            url: &quot;rack_action.php&quot;,
            method: &quot;POST&quot;,
            data: formData,
            success: function (data) {
                jQuery('#rackForm')[0].reset();
                jQuery('#rackModal').modal('hide');
                jQuery('#save').attr('disabled', false);
                rackRecords.ajax.reload();
            }
        })
    });

    jQuery(&quot;#rackListing&quot;).on('click', '.delete', function () {
        var rackid = jQuery(this).attr(&quot;id&quot;);
        var action = &quot;deleteRack&quot;;
        if (confirm(&quot;Are you sure you want to delete this record?&quot;)) {
            jQuery.ajax({
                url: &quot;rack_action.php&quot;,
                method: &quot;POST&quot;,
                data: { rackid: rackid, action: action },
                success: function (data) {
                    rackRecords.ajax.reload();
                }
            })
        } else {
            return false;
        }
    });

});</pre>
<div class="top-line-bold">Create files named (header.php and footer.php)</div>

<div class="new-line-label">This file contains the header and footer section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.</div>
<div class="top-line-bold">header.php</div>
<pre class="crayon-plain-tag">&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;

&lt;head&gt;
  &lt;link rel=&quot;canonical&quot; href=&quot;https://techarise.com/&quot; /&gt;
  &lt;meta name=&quot;author&quot; content=&quot;TechArise&quot;&gt;
  &lt;meta name=&quot;description&quot; content=&quot;Learn Web Development Tutorials &amp; Web Developer Resources, PHP, MySQL, jQuery, CSS, XHTML, jQuery UI, CSS3, HTML5, HTML, web design, webdesign, with TechArise tutorials. View live demo&quot;&gt;
  &lt;meta name=&quot;keywords&quot; content=&quot;TechArise, tutorial TechArise, tutorials, freebies, resources, web development, webdev, demo, PHP, MySQL, jQuery, CSS, XHTML, jQuery UI, CSS3, HTML5, HTML, web design, webdesign, php script, dynamic web content&quot; /&gt;
  &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
  &lt;link rel=&quot;icon&quot; type=&quot;image/ico&quot; href=&quot;https://techarise.com/wp-content/themes/v1/favicon.ico&quot;&gt;
  &lt;!-- Bootstrap CSS --&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css&quot;&gt;
  &lt;link href=&quot;http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css&quot; rel=&quot;stylesheet&quot;&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.datatables.net/responsive/2.2.9/css/responsive.bootstrap4.min.css&quot; /&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.datatables.net/1.11.3/css/dataTables.bootstrap4.min.css&quot; /&gt;
  &lt;!--- Custom css ---&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;css/style.css&quot; /&gt;
  &lt;title&gt;Library Management System | Tech Arise&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
  &lt;?php include('menus.php'); ?&gt;</pre>

<div class="top-line-bold">menus.php</div>
<pre class="crayon-plain-tag">&lt;header style=&quot;margin-bottom:65px;&quot;&gt;
    &lt;!-- Fixed navbar --&gt;
    &lt;nav class=&quot;navbar navbar-expand-md navbar-dark fixed-top bg-dark&quot; style=&quot;background: #273E4A!important;&quot;&gt;
        &lt;a class=&quot;navbar-brand&quot; href=&quot;https://techarise.com&quot;&gt;&lt;strong&gt;Tech Arise&lt;/strong&gt;&lt;/a&gt;
        &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navbarCollapse&quot; aria-controls=&quot;navbarCollapse&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation&quot;&gt;
            &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;
        &lt;/button&gt;
        &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarCollapse&quot;&gt;
            &lt;ul class=&quot;navbar-nav mr-auto&quot;&gt;
                &lt;li class=&quot;nav-item active&quot;&gt;
                    &lt;a class=&quot;nav-link&quot; href=&quot;https://techarise.com&quot;&gt;Home &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;&lt;/a&gt;
                &lt;/li&gt;
            &lt;/ul&gt;
            &lt;?php if (!empty($_SESSION) &amp;&amp; $_SESSION[&quot;userid&quot;]) { ?&gt;
            &lt;span class=&quot;nav-item dropdown&quot;&gt;
                &lt;a style=&quot;color:#fff;&quot; class=&quot;nav-link&quot; href=&quot;logout.php&quot; id=&quot;navbarDropdown&quot; role=&quot;button&quot; data-toggle=&quot;dropdown&quot; aria-haspopup=&quot;true&quot; aria-expanded=&quot;false&quot;&gt;
                    &lt;i class=&quot;fa fa-user&quot;&gt;&lt;/i&gt; &lt;?php echo ucfirst($_SESSION[&quot;name&quot;]); ?&gt;
                &lt;/a&gt;
            &lt;/span&gt;
            &lt;?php } ?&gt;
        &lt;/div&gt;
    &lt;/nav&gt;
&lt;/header&gt;</pre>

<div class="top-line-bold">footer.php</div>
<pre class="crayon-plain-tag">&lt;footer class=&quot;footer&quot;&gt;
&lt;div class=&quot;container&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;/footer&gt;
&lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdn.datatables.net/1.11.3/js/dataTables.bootstrap4.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdn.datatables.net/responsive/2.2.9/js/responsive.bootstrap4.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/books.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/category.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/author.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/publisher.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/rack.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/issue_books.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/user.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;

&lt;/html&gt;</pre>

<div class="ex-read-more">
    <a href="https://techarise.com/codeigniter-authentication-login-registration/" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
            Also Read : Codeigniter 4 Authentication Login and Registration
        </div>
    </a>
</div>

<div class="new-line-label">
    <a class="btn btn-success" title="Demo" href="https://techarise.com/demos/php/library-management-system" target="_balnk" rel="noopener noreferrer"><i class="fa fa-fw fa-eye"></i> Demo</a>

    <a class="btn btn-primary" title="Download" href="https://techarise.com/source-code/download/library-management-0A9DF635-894Z-4590-0402" target="_balnk" rel="noopener noreferrer"><i class="fa fa-fw fa-download text-right"></i> Download</a>
</div><p>The post <a href="https://techarise.com/library-management-system-in-php-and-mysql/">Library Management System in PHP and MySQL</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></content:encoded>
					
		
		
			<dc:creator>techariseinfo@gmail.com (TechArise Team)</dc:creator></item>
		<item>
		<title>NodeJS RESTfull APIs with Express and MySQL</title>
		<link>https://techarise.com/nodejs-restfull-apis-with-express-and-mysql/</link>
		
		
		<pubDate>Sat, 14 Oct 2023 04:43:15 +0000</pubDate>
				<category><![CDATA[API]]></category>
		<category><![CDATA[Node JS]]></category>
		<category><![CDATA[REST API]]></category>
		<guid isPermaLink="false">https://techarise.com/?p=1272</guid>

					<description><![CDATA[<p>RESTful web APIs are typically loosely based on HTTP methods to access resources via URL-encoded parameters and the use of&#8230;</p>
<p>The post <a href="https://techarise.com/nodejs-restfull-apis-with-express-and-mysql/">NodeJS RESTfull APIs with Express and MySQL</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></description>
										<content:encoded><![CDATA[<div class="new-line-label">RESTful web APIs are typically loosely based on HTTP methods to access resources via URL-encoded parameters and the use of <code>JSON</code> or <code>XML</code> to transmit data. RESTful Web services are one way of providing interoperability between computer systems on the Internet. Rest API helps to communicate between the client app and the server application. REST is an architecture style for designing networked applications. A REST API defines a bunch of functions which developers can perform requests and receive responses via HTTP protocol such as GET and POST.</div>

<div class="new-line-label">In this tutorial, you will learn to how create CRUD (create, read, update, delete) operation RESTful APIs NodeJS with Express and MySQL. This is a very simple example, you can just copy-paste, and change according to your requirements.</div>

<div class="ex-read-more new-line-label">
    <a href="https://techarise.com/build-simple-rest-api-with-php-mysql/" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
           Also Read : Build Simple REST API with PHP and MySQL
        </div>
    </a>
</div>

<div class="top-line-bold">Before started to implement the NodeJS RESTfull APIs with Express and MySQL, look files structure:</div>

<ul class="tree-structure"> 
  <li><i class="folder-color fa fa-folder"></i> nodejs-express-mysql-restfull-api
  <ul>
        
    <li><i class="folder-color fa fa-folder"></i> application
      <ul>
        <li><i class="folder-color fa fa-folder"></i> config
          <ul>
             <li><i class="text-muted far fa-file"></i> db.config.js</li>
        </ul>
        </li>
        

        <li><i class="folder-color fa fa-folder"></i> models
          <ul>
             <li><i class="text-muted far fa-file"></i> news.model.js</li>
        </ul>
        </li>

        <li><i class="folder-color fa fa-folder"></i> controllers
          <ul>
             <li><i class="text-muted far fa-file"></i> news.controller.js</li>
        </ul>
        </li>

        <li><i class="folder-color fa fa-folder"></i> routes
          <ul>
             <li><i class="text-muted far fa-file"></i> routes.js</li>
        </ul>
        </li>          
      </ul>      
    </li> 
    <li><i class="folder-color fa fa-folder"></i> node_modules</li> 
    <li><i class="text-muted far fa-file"></i> .env</li> 
    <li><i class="text-muted far fa-file"></i> index.js</li> 
    <li><i class="text-muted far fa-file"></i> package.json</li> 
    <li><i class="text-muted far fa-file"></i> package-lock.json</li> 
    <li><i class="text-muted far fa-file"></i> README.md</li> 
  </ul>
</li>
</ul>


<div class="new-line-bold">Understanding REST API</div>
<div class="new-line-label">REST provides a block of HTTP methods which are used to alter the data. The following are common HTTP methods:</div>
<ul style="padding-left:30px;">
  <li><strong>GET</strong> — is used for reading and retrieving data.</li>
  <li><strong>POST</strong> — is used for inserting data.</li>
  <li><strong>PUT/PATCH</strong> — is used for updating data.</li>
  <li><strong>DELETE</strong> — is used for deleting data.</li>
</ul>

<div class="new-line-bold">Step 1: Create MySQL Database and Table </div>
<div class="new-line-label">For this tutorial, you need a MySQL database with the following table: </div>
<pre class="crayon-plain-tag">CREATE TABLE `news` (
    `id` int(11) NOT NULL,
    `title` text NOT NULL,
    `description` text NOT NULL,
    `status` int(1) NOT NULL,
    `publish_date` varchar(12) DEFAULT NULL,
    `created_date` varchar(12) DEFAULT NULL,
    `modified_date` varchar(12) DEFAULT NULL
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

  INSERT INTO `news` (`id`, `title`, `description`, `status`, `publish_date`, `created_date`, `modified_date`) VALUES
(1, 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.', 1, '1634369809', '1634369809', '1634369809');


  ALTER TABLE `news`
    ADD PRIMARY KEY (`id`);

  ALTER TABLE `news`
    MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
  COMMIT;</pre>

<div class="new-line-bold">Set Up and Run a Simple Node Server</div>
<div class="new-line-label">Let&#8217;s build our web server. Create a file named <code>index.js</code></div>
<pre class="crayon-plain-tag">const express = require(&quot;express&quot;);
    const dotenv = require('dotenv');
    const app = express();
    // dotenv config
    dotenv.config();
    // ContentTypeParser: parse requests of content-type - application/json
    app.use(express.json());

    // ContentTypeParser: parse requests of content-type - application/x-www-form-urlencoded
    app.use(express.urlencoded({ extended: true }));

    // create route
    app.get(&quot;/&quot;, (req, res) =&gt; {
      res.json({ message: &quot;TechArise - NodeJS RESTfull APIs with Express and MySQL&quot; });
    });

    require(&quot;./application/routes/routes.js&quot;)(app);

    // set port, listen 
    const PORT = Number(process.env.PORT || 3000);


    app.listen(PORT, () =&gt; {
      console.log(`Server is running on PORT ${PORT}.`);
    });</pre>
<div class="new-line-bold">Step 2: Create file named <code>.env</code></div>
<div class="new-line-label">loads environment variables</div>
<pre class="crayon-plain-tag"># DB Configurations
  HOST=localhost
  DB_USER=root
  DB_PASS=
  DB_DATABASE=newsapi_DB

  # local runtime configs
  PORT=9090
  SECRET_JWT=supersecret</pre>

<div class="new-line-bold">Step 3: Connect to Database file named <code>db.config.js</code>  inside “application/config/” folder.</div>
<div class="new-line-label">The code below shows the database credentials</div>
<pre class="crayon-plain-tag">const mysql = require(&quot;mysql&quot;);
const dotenv = require('dotenv');
dotenv.config();

// create MySQL Connection
var connection = mysql.createPool({
  host: process.env.HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASS,
  database: process.env.DB_DATABASE
});

module.exports = connection;</pre>


<div class="new-line-bold">Step 4: Create models </div>
<div class="new-line-label">Create a models file named <code>news.model.js</code> inside “application/models/”  folder.</div>
<ul style="padding-left:30px;">
    <li><strong>The News class handles the CRUD process</strong></li>
    <li><code>constructor</code> —  called an object</li>
    <li>Add News Record in database.</li>
    <li>Update News Record in databae.</li>
    <li>News all Records from database.</li>
    <li>get News single Record from database.</li>
    <li>delete News Record from database.</li>
</ul>

<pre class="crayon-plain-tag">const sql = require(&quot;../config/db.config.js&quot;);
   
    // constructor
    class News {
      constructor(news) {
        this.title = news.title;
        this.description = news.description;
        this.status = news.status;
        this.publish_date = news.publish_date;
        this.created_date = news.created_date;
        this.modified_date = news.modified_date;
      }
      // create new news
      static create(newNews, result) {
        sql.query(&quot;INSERT INTO news SET ?&quot;, newNews, (err, res) =&gt; {
          if (err) {
            console.log(&quot;error: &quot;, err);
            result(err, null);
            return;
          }

          console.log(&quot;created news: &quot;, { id: res.insertId, ...newNews });
          result(null, { id: res.insertId, ...newNews });
        });
      }
      // get single news
      static findById(newsId, result) {
        sql.query(`SELECT * FROM news WHERE id = ${newsId}`, (err, res) =&gt; {
          if (err) {
            console.log(&quot;error: &quot;, err);
            result(err, null);
            return;
          }

          if (res.length) {
            console.log(&quot;found news: &quot;, res[0]);
            result(null, res[0]);
            return;
          }

          // not found news with the id
          result({ kind: &quot;not_found&quot; }, null);
        });
      }
      // get all news
      static getAll(result) {
        sql.query(&quot;SELECT * FROM news&quot;, (err, res) =&gt; {
          if (err) {
            console.log(&quot;error: &quot;, err);
            result(null, err);
            return;
          }

          console.log(&quot;news: &quot;, res);
          result(null, res);
        });
      }
      // update news
      static updateById(id, news, result) {
        sql.query(
          &quot;UPDATE news SET title = ?, description = ?, status = ?, publish_date = ?, created_date = ?, modified_date = ? WHERE id = ?&quot;,
          [news.title, news.description, news.status, publish_date.address, news.created_date, news.modified_date, id],
          (err, res) =&gt; {
            if (err) {
              console.log(&quot;error: &quot;, err);
              result(null, err);
              return;
            }

            if (res.affectedRows == 0) {
              // not found news with the id
              result({ kind: &quot;not_found&quot; }, null);
              return;
            }

            console.log(&quot;updated news: &quot;, { id: id, ...news });
            result(null, { id: id, ...news });
          }
        );
      }
      // delete news
      static remove(id, result) {
        sql.query(&quot;DELETE FROM news WHERE id = ?&quot;, id, (err, res) =&gt; {
          if (err) {
            console.log(&quot;error: &quot;, err);
            result(null, err);
            return;
          }

          if (res.affectedRows == 0) {
            // not found news with the id
            result({ kind: &quot;not_found&quot; }, null);
            return;
          }

          console.log(&quot;deleted news with id: &quot;, id);
          result(null, res);
        });
      }
      // delete all news
      static removeAll(result) {
        sql.query(&quot;DELETE FROM news&quot;, (err, res) =&gt; {
          if (err) {
            console.log(&quot;error: &quot;, err);
            result(null, err);
            return;
          }

          console.log(`deleted ${res.affectedRows} news`);
          result(null, res);
        });
      }
    }
    module.exports = News;</pre>

<div class="new-line-bold">Step 5: Create controllers </div>
<div class="new-line-label">Create a controllers file named <code>news.controller.js</code> inside “application/controllers/”  folder.</div>


<pre class="crayon-plain-tag">// include news model
    const News = require(&quot;../models/news.model.js&quot;);

    // Add and Save a new News method
    exports.create = (req, res) =&gt; {
      // Validate request
      if (!req.body) {
        res.status(400).send({
          message: &quot;Error: Content can not be empty!&quot;
        });
      }

      // Create a News
      const news = new News({
        title: req.body.title,
        description: req.body.description,
        status: req.body.status,
        publish_date: req.body.publish_date,
        created_date: req.body.created_date,
        modified_date: req.body.modified_date
      });

      // Save News in the database
      News.create(news, (err, data) =&gt; {
        if (err)
          res.status(500).send({
            message:
              err.message || &quot;Error while creating news.&quot;
          });
        else res.send(data);
      });
    };

    // get all News from the database.
    exports.findAll = (req, res) =&gt; {
      News.getAll((err, data) =&gt; {
        if (err)
          res.status(500).send({
            message:
              err.message || &quot;Error while retrieving news.&quot;
          });
        else res.send(data);
      });
    };

    // Find a single News with a newsId
    exports.findOne = (req, res) =&gt; {
      News.findById(req.params.newsId, (err, data) =&gt; {
        if (err) {
          if (err.kind === &quot;not_found&quot;) {
            res.status(404).send({
              message: `News record not found ID: ${req.params.newsId}.`
            });
          } else {
            res.status(500).send({
              message: &quot;Error retrieving News ID &quot; + req.params.newsId
            });
          }
        } else res.send(data);
      });
    };

    // Update a News records 
    exports.update = (req, res) =&gt; {
      // Validate Request
      if (!req.body) {
        res.status(400).send({
          message: &quot;Error: Content can not be empty!&quot;
        });
      }

      console.log(req.body);

      News.updateById(
        req.params.newsId,
        new News(req.body),
        (err, data) =&gt; {
          if (err) {
            if (err.kind === &quot;not_found&quot;) {
              res.status(404).send({
                message: `News record not found ID: ${req.params.newsId}.`
              });
            } else {
              res.status(500).send({
                message: &quot;Error: updating News ID: &quot; + req.params.newsId
              });
            }
          } else res.send(data);
        }
      );
    };

    // Delete a News with the specified newsId in the request
    exports.delete = (req, res) =&gt; {
      News.remove(req.params.newsId, (err, data) =&gt; {
        if (err) {
          if (err.kind === &quot;not_found&quot;) {
            res.status(404).send({
              message: `News record not found ID: ${req.params.newsId}.`
            });
          } else {
            res.status(500).send({
              message: &quot;Could not delete News ID: &quot; + req.params.newsId
            });
          }
        } else res.send({ message: `News was deleted successfully!` });
      });
    };

    // Delete all News from the database.
    exports.deleteAll = (req, res) =&gt; {
      News.removeAll((err, data) =&gt; {
        if (err)
          res.status(500).send({
            message:
              err.message || &quot;Error occurred while removing all news.&quot;
          });
        else res.send({ message: `Delete all News successfully!` });
      });
    };</pre>
<div class="new-line-bold">Step 6: Create routes </div>
<div class="new-line-label">Create a routes file named <code>routes.js</code> inside “application/routes/”  folder.</div>
<pre class="crayon-plain-tag">module.exports = app =&gt; {
  const news = require(&quot;../controllers/news.controller.js&quot;);

  // Add a new news in database
  app.post(&quot;/news/create&quot;, news.create);

  // Fetch all News for database
  app.get(&quot;/news&quot;, news.findAll);

  // Fetch data a single News form database
  app.get(&quot;/news/:newsId&quot;, news.findOne);

  // Update a News records
  app.put(&quot;/news/update/:newsId&quot;, news.update);

  // Delete a News records
  app.delete(&quot;/news/delete/:newsId&quot;, news.delete);

  // Delete All News records
  app.delete(&quot;/news/delete&quot;, news.deleteAll);
};</pre>
<br>

<div class="new-line-bold">Run Application</div>
<div class="new-line-label">Now we will use Postman to run  RESTful APIs.</div>

<div class="new-line-bold">POST Method: Save News in the database</div>
<pre class="crayon-plain-tag">// POST Method
  http://localhost:9090/news/create

  // Body JSON
  {
    &quot;title&quot;: &quot;Lorem Ipsum is simply dummy text of the printing and typesetting industry.&quot;,
    &quot;description&quot;: &quot;Lorem Ipsum is simply dummy text of the printing and typesetting industry.&quot;,
    &quot;status&quot; : 1,
    &quot;publish_date&quot;: &quot;1634369809&quot;,
    &quot;created_date&quot;: &quot;1634369809&quot;,
    &quot;modified_date&quot;: &quot;1634369809&quot;
  }</pre>

<div class="new-line-bold">GET method: Find a single News with a newsId.</div>
<pre class="crayon-plain-tag">// GET Method
  http://localhost:9090/news/1
  
  // Response JSON
  {
    &quot;title&quot;: &quot;Lorem Ipsum is simply dummy text of the printing and typesetting industry.&quot;,
    &quot;description&quot;: &quot;Lorem Ipsum is simply dummy text of the printing and typesetting industry.&quot;,
    &quot;status&quot; : 1,
    &quot;publish_date&quot;: &quot;1634369809&quot;,
    &quot;created_date&quot;: &quot;1634369809&quot;,
    &quot;modified_date&quot;: &quot;1634369809&quot;
  }</pre>


<div class="new-line-bold">GET method: Get all News from the database.</div>
<pre class="crayon-plain-tag">// GET Method
  http://localhost:9090/news
  
  // Response JSON
  [
    {
      &quot;title&quot;: &quot;Lorem Ipsum is simply dummy text of the printing and typesetting industry.&quot;,
      &quot;description&quot;: &quot;Lorem Ipsum is simply dummy text of the printing and typesetting industry.&quot;,
      &quot;status&quot; : 1,
      &quot;publish_date&quot;: &quot;1634369809&quot;,
      &quot;created_date&quot;: &quot;1634369809&quot;,
      &quot;modified_date&quot;: &quot;1634369809&quot;
    }
  ]</pre>

<div class="new-line-bold">PUT Method: Update a News records </div>
<pre class="crayon-plain-tag">// PUT Method
  http://localhost:9090/news/update/1
  
  // Body JSON
  {
    &quot;title&quot;: &quot;update_Lorem Ipsum is simply dummy text of the printing and typesetting industry.&quot;,
    &quot;description&quot;: &quot;update_Lorem Ipsum is simply dummy text of the printing and typesetting industry.&quot;,
    &quot;status&quot; : 1,
    &quot;publish_date&quot;: &quot;1634369801&quot;,
    &quot;created_date&quot;: &quot;1634369801&quot;,
    &quot;modified_date&quot;: &quot;1634369801&quot;
  }</pre>

<div class="new-line-bold">DELETE Method: Delete a News with the specified newsId in the request </div>
<pre class="crayon-plain-tag">// DELETE Method
  http://localhost:9090/news/delete/1
  // Message
  {
    &quot;message&quot;: &quot;News was deleted successfully!&quot;
  }</pre>

<div class="new-line-bold">DELETE Method: Delete all News from the database. </div>
<pre class="crayon-plain-tag">// DELETE Method
  http://localhost:9090/news/delete
  // Message
  {
    &quot;message&quot;: &quot;Delete all News successfully!&quot;
  }</pre>


<div class="ex-read-more new-line-label">
    <a href="https://techarise.com/restful-api-using-python-mysql" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
           Also Read : Build Simple RESTful API using Python and MySQL
        </div>
    </a>
</div>


<div class="new-line-label">
     <a class="btn btn-primary" title="Download" href="https://techarise.com/source-code/download/nodejs-rest-apis-0A9DF635-894Z-4590-0399" target="_balnk" rel="noopener noreferrer"><i class="fa fa-fw fa-download text-right"></i> Download</a>
</div><p>The post <a href="https://techarise.com/nodejs-restfull-apis-with-express-and-mysql/">NodeJS RESTfull APIs with Express and MySQL</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></content:encoded>
					
		
		
			<dc:creator>techariseinfo@gmail.com (TechArise Team)</dc:creator></item>
		<item>
		<title>How to get current date, given a timezone in PHP</title>
		<link>https://techarise.com/how-to-get-current-date-given-a-timezone-in-php/</link>
		
		
		<pubDate>Sat, 07 Oct 2023 08:36:53 +0000</pubDate>
				<category><![CDATA[How To Guides]]></category>
		<guid isPermaLink="false">https://techarise.com/?p=1462</guid>

					<description><![CDATA[<p>PHP date() function is an in-built function that simplifies working with date data types. The PHP date() function is used&#8230;</p>
<p>The post <a href="https://techarise.com/how-to-get-current-date-given-a-timezone-in-php/">How to get current date, given a timezone in PHP</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></description>
										<content:encoded><![CDATA[<div class="new-line-label">PHP <code>date()</code> function is an in-built function that simplifies working with date data types. The PHP <code>date()</code> function is used to format a date/time into a human-readable format.</div>

<div class="new-line-label">In this tutorial, We will show you how to get the current date, given a timezone in PHP. Using PHP, you can get and display the current Date and Time from a specific timezone.</div>

<div class="ex-read-more">
    <a href="https://techarise.com/how-to-get-current-url-in-php" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
            Also Read: How to Get Current URL in PHP
        </div>
    </a>
</div>

<ul style="padding-left: 20px;">
    <li>Create a new DateTime object with PHP.</li>
	<li>Convert the DateTime object to the timezone of New_York using the <code>DateTimeZone</code> object.</li>
	<li>Specify the date and time format.</li>
</ul>

<div class="new-line-label">Here&#8217;s an example of how to do this:</div>
<pre class="crayon-plain-tag">// Set the timezone to &quot;America/New_York&quot;
$date = new DateTime(&quot;now&quot;, new DateTimeZone('America/New_York') );

// Get the current date and time in the specified timezone
$dateTime = $date-&gt;format('Y-m-d H:i:s');

echo $dateTime;</pre>
<div class="new-line-label">You can change the timezone in the DateTimeZone object and adjust the date format in the <code>format()</code> function.</div>

<div class="ex-read-more">
    <a href="https://techarise.com/how-to-disable-browser-back-button-using-javascript" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
            Also Read: How to Disable Browser Back Button using JavaScript
        </div>
    </a>
</div>
<br><p>The post <a href="https://techarise.com/how-to-get-current-date-given-a-timezone-in-php/">How to get current date, given a timezone in PHP</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></content:encoded>
					
		
		
			<dc:creator>techariseinfo@gmail.com (TechArise Team)</dc:creator></item>
		<item>
		<title>Laravel 9 Registration and Login using MySQL</title>
		<link>https://techarise.com/laravel-registration-login/</link>
		
		
		<pubDate>Sat, 14 Jan 2023 18:44:29 +0000</pubDate>
				<category><![CDATA[Laravel]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Laravel login]]></category>
		<category><![CDATA[Laravel registration]]></category>
		<guid isPermaLink="false">https://techarise.com/?p=1435</guid>

					<description><![CDATA[<p>Registration and login were separated, the user firstly needs to register and set the password accordingly. Through such a method&#8230;</p>
<p>The post <a href="https://techarise.com/laravel-registration-login/">Laravel 9 Registration and Login using MySQL</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></description>
										<content:encoded><![CDATA[<div class="new-line-label">Registration and login were separated, the user firstly needs to register and set the password accordingly. Through such a method it can gain the user’s password information while making login through multiple platforms which shall bring a better user experience. In this tutorial, we will explain how to create a user Registration and Login Module in Laravel 9 using MySQL. This is a very simple example, you can just copy-paste and change it according to your requirement.</div>

<div class="ex-read-more">
    <a href="https://techarise.com/full-featured-registration-login-module-codeigniter/" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
            Also Read : Create a Full Featured Registration and Login Module in CodeIgniter
        </div>
    </a>
</div>

<div class="new-line-label">Before started to implement the Registration and Login Module in Laravel 9 using MySQL, look files structure:</div>
<ul class="tree-structure">
    <li><i class="folder-color fa fa-folder"></i> laravel-registration-login
        <ul>
            <li><i class="folder-color fa fa-folder"></i> app
                <ul>
                    <li><i class="folder-color fa fa-folder"></i> Console</li>
                    <li><i class="folder-color fa fa-folder"></i> Exceptions</li>
                    <li><i class="folder-color fa fa-folder"></i> Http
                        <ul>
                            <li><i class="folder-color fa fa-folder"></i> Controllers
                                <ul>
                                    <li><i class="folder-color fa fa-folder"></i> Auth
                                        <ul>
                                            <li><i class="text-muted far fa-file"></i> AuthController.php</li>
                                        </ul>
                                    </li>
                                </ul>
                            </li>
                        </ul>
                    </li>
                    <li><i class="folder-color fa fa-folder"></i> Models
                        <ul>
                            <li><i class="folder-color fa fa-folder"></i> User.php
                            </li>
                        </ul>
                    </li>
                    <li><i class="folder-color fa fa-folder"></i> Providers</li>
                </ul>

            </li>
            <li><i class="folder-color fa fa-folder"></i> resources</li>
            <li><i class="folder-color fa fa-folder"></i> config</li>
            <li><i class="folder-color fa fa-folder"></i> database</li>
            <li><i class="folder-color fa fa-folder"></i> public
                <ul>
                    <li><i class="folder-color fa fa-folder"></i> assets
                        <ul>
                            <li><i class="folder-color fa fa-folder"></i> css
                                <ul>
                                    <li><i class="text-muted far fa-file"></i> style.css</li>
                                </ul>
                            </li>
                            <li><i class="folder-color fa fa-folder"></i> images</li>
                            <li><i class="folder-color fa fa-folder"></i> js
                                <ul>
                                    <li><i class="text-muted far fa-file"></i> app.js</li>
                                </ul>
                            </li>
                        </ul>
                    </li>

                </ul>
                <ul>
                    <li><i class="text-muted far fa-file"></i> .htaccess</li>
                    <li><i class="text-muted far fa-file"></i> index.php</li>
                </ul>
            </li>
            <li><i class="folder-color fa fa-folder"></i> resources
                <ul>
                    <li><i class="folder-color fa fa-folder"></i> views
                        <ul>
                            <li><i class="text-muted far fa-file"></i> dashboard.blade.php</li>
                            <li><i class="text-muted far fa-file"></i> layout.blade.php</li>
                        </ul>
                        <ul>
                            <li><i class="folder-color fa fa-folder"></i> auth
                                <ul>
                                    <li><i class="text-muted far fa-file"></i> login.blade.php</li>
                                    <li><i class="text-muted far fa-file"></i> registration.blade.php</li>
                                </ul>
                            </li>
                        </ul>

                    </li>
                </ul>
            </li>

            <li><i class="folder-color fa fa-folder"></i> routes
                <ul>
                    <li><i class="text-muted far fa-file"></i> api.php</li>
                    <li><i class="text-muted far fa-file"></i> channels.php</li>
                    <li><i class="text-muted far fa-file"></i> console.php</li>
                    <li><i class="text-muted far fa-file"></i> web.php</li>
                </ul>
            </li>
            <li><i class="folder-color fa fa-folder"></i>storage</li>
            <li><i class="folder-color fa fa-folder"></i>tests</li>
            <li><i class="folder-color fa fa-folder"></i>vendor</li>
            <li><i class="text-muted far fa-file"></i> .env</li>
            <li><i class="text-muted far fa-file"></i> server.php</li>
        </ul>
    </li>
</ul>

<div class="new-line-label">Follow the following steps and build Login and Registration process in Laravel:</div>

<ul style="padding-left: 20px;">
    <li>Step 1 – Firstly, Install Laravel Application</li>
    <li>Step 2 – Configure Database</li>
    <li>Step 3 – Create Controller and Methods.</li>
    <li>Step 4 – Create Routes</li>
    <li>Step 5 – Create Blade Views</li>
    <li>Step 6 – Finally, Run Laravel Application</li>
</ul>

<div class="new-line-bold">Step 1 – Install Laravel 9 Application</div>

<div class="new-line-label">To handle the actual install you would use the following command in your terminal the Laravel application.</div>

<pre class="crayon-plain-tag">composer create-project --prefer-dist laravel/laravel laravel-registration-login</pre>

<div class="new-line-bold">Step 2: Setup and Configure Database access</div>
<div class="new-line-label">Go to app directory and open .env file. And add/update database credentials:</div>
<pre class="crayon-plain-tag">DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=demo_DB
    DB_USERNAME=root
    DB_PASSWORD=</pre>

<div class="new-line-bold">Next, migrate the table into the database using the below command :</div>
<pre class="crayon-plain-tag">php artisan migrate</pre>

<div class="new-line-bold">Step 3: Create controllers</div>
<div class="new-line-label">Create a controllers file named AuthController.php inside &#8220;app\Http\Controllers\Auth&#8221; folder. </div>
<pre class="crayon-plain-tag">&lt;?php

/**
 * Description of Users Controller
 *
 * @author Team TechArise
 *
 * @email info@techarise.com
 */

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;
use App\Models\User;
use Hash;

class AuthController extends Controller
{
    // code login method
    public function index()
    {
        return view('auth.login');
    }
    // code registration method
    public function registration()
    {
        return view('auth.registration');
    }

    // code action login method
    public function actionLogin(Request $request)
    {
        $request-&gt;validate([
            'email' =&gt; 'required',
            'password' =&gt; 'required',
        ]);

        $credentials = $request-&gt;only('email', 'password');
        if (Auth::attempt($credentials)) {
            return redirect()-&gt;intended('dashboard')
                -&gt;withSuccess('You have Successfully loggedin');
        }
        return redirect(&quot;login&quot;)-&gt;withSuccess('Please enter valid credentials');
    }

    // code action registration method
    public function actionRegistration(Request $request)
    {
        $request-&gt;validate([
            'name' =&gt; 'required',
            'email' =&gt; 'required|email|unique:users',
            'password' =&gt; 'required|min:6',
        ]);

        $data = $request-&gt;all();
        $check = $this-&gt;create($data);
        return redirect(&quot;dashboard&quot;)-&gt;withSuccess('You have Successfully logged-in');
    }

    // code dashboard method
    public function dashboard()
    {
        if (Auth::check()) {
            return view('dashboard');
        }
        return redirect(&quot;login&quot;)-&gt;withSuccess('You do not have access');
    }

    // code create method
    public function create(array $data)
    {
        return User::create([
            'name' =&gt; $data['name'],
            'email' =&gt; $data['email'],
            'password' =&gt; Hash::make($data['password'])
        ]);
    }

    // code logout method
    public function logout()
    {
        Session::flush();
        Auth::logout();
        return Redirect('login');
    }
}


?&gt;</pre>

<div class="new-line-bold">Step 4: Create Routes</div>
<div class="new-line-label">Add/Update code the file named web.php inside &#8220;routes/&#8221; folder</div>
<pre class="crayon-plain-tag">&lt;?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\Auth\AuthController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the &quot;web&quot; middleware group. Now create something great!
|
*/
// custom create routes 
Route::get('/', [AuthController::class, 'index'])-&gt;name('login');
Route::get('login', [AuthController::class, 'index'])-&gt;name('login');
Route::post('action-login', [AuthController::class, 'actionLogin'])-&gt;name('login.action');
Route::get('registration', [AuthController::class, 'registration'])-&gt;name('register');
Route::post('action-registration', [AuthController::class, 'actionRegistration'])-&gt;name('register.action');
Route::get('dashboard', [AuthController::class, 'dashboard']);
Route::get('logout', [AuthController::class, 'logout'])-&gt;name('logout');

?&gt;</pre>

<div class="new-line-bold">Step 6: Create Blade Views </div>
<div class="new-line-label">This file contains the header and footer sections of the webpage. The Bootstrap library is used to provide a better UI.</div>
<div class="new-line-label"><strong>i</strong> &#8211; Create(layout) a views file named layout.blade.php inside &#8220;resources\views\&#8221; folder. </div>
<pre class="crayon-plain-tag">&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;

&lt;head&gt;
    &lt;link rel=&quot;canonical&quot; href=&quot;https://techarise.com/&quot; /&gt;
    &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
    &lt;link rel=&quot;icon&quot; type=&quot;image/ico&quot; href=&quot;https://techarise.com/wp-content/themes/v1/favicon.ico&quot;&gt;
    &lt;!-- Bootstrap CSS --&gt;
    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC&quot; crossorigin=&quot;anonymous&quot;&gt;
    &lt;!--- Custom css ---&gt;
    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;{{ url('/assets/css/sticky-footer-navbar.css') }}&quot; /&gt;
    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;{{ url('/assets/css/style.css') }}&quot; /&gt;

    &lt;title&gt;Laravel 9 Login and Registration | Tech Arise&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
    &lt;header&gt;
        &lt;nav class=&quot;navbar navbar-expand-md navbar-dark fixed-top bg-dark&quot;&gt;
            &lt;div class=&quot;container-fluid&quot;&gt;
                &lt;a class=&quot;navbar-brand&quot; href=&quot;https://techarise.com&quot;&gt;TechArise&lt;/a&gt;
                &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-bs-toggle=&quot;collapse&quot; data-bs-target=&quot;#navbarCollapse&quot; aria-controls=&quot;navbarCollapse&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation&quot;&gt;
                    &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;
                &lt;/button&gt;
                &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarCollapse&quot;&gt;
                    &lt;ul class=&quot;navbar-nav me-auto mb-2 mb-md-0&quot;&gt;
                        &lt;li class=&quot;nav-item&quot;&gt;
                            &lt;a class=&quot;nav-link active&quot; aria-current=&quot;page&quot; href=&quot;https://techarise.com&quot;&gt;Home&lt;/a&gt;
                        &lt;/li&gt;
                        @guest
                        &lt;li class=&quot;nav-item&quot;&gt;
                            &lt;a class=&quot;nav-link&quot; href=&quot;{{ route('login') }}&quot;&gt;Login&lt;/a&gt;
                        &lt;/li&gt;
                        &lt;li class=&quot;nav-item&quot;&gt;
                            &lt;a class=&quot;nav-link&quot; href=&quot;{{ route('register') }}&quot;&gt;Register&lt;/a&gt;
                        &lt;/li&gt;
                        @else
                        &lt;li class=&quot;nav-item&quot;&gt;
                            &lt;a class=&quot;nav-link&quot; href=&quot;{{ route('logout') }}&quot;&gt;Logout&lt;/a&gt;
                        &lt;/li&gt;
                        @endguest
                    &lt;/ul&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/nav&gt;
    &lt;/header&gt;

    @yield('content')

    &lt;footer class=&quot;footer&quot;&gt;
        &lt;div class=&quot;container&quot;&gt;&amp;nbsp;&lt;/div&gt;
    &lt;/footer&gt;

    &lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.js&quot; integrity=&quot;sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js&quot; integrity=&quot;sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js&quot; integrity=&quot;sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;

&lt;/body&gt;

&lt;/html&gt;</pre>

<div class="new-line-label"><strong>ii</strong> &#8211; Create(login) a views file named login.blade.php inside &#8220;resources\views\auth\&#8221; folder. </div>
<pre class="crayon-plain-tag">@extends('layout')

@section('content')

&lt;main class=&quot;flex-shrink-0&quot;&gt;
    &lt;div class=&quot;container mt-5&quot;&gt;
        &lt;div class=&quot;row justify-content-center&quot;&gt;
            &lt;div class=&quot;col-md-8&quot;&gt;
                &lt;h2 class=&quot;mt-5 text-center&quot;&gt;Laravel 9 Login and Registration&lt;/h2&gt;
                &lt;div class=&quot;card&quot;&gt;
                    &lt;div class=&quot;card-header&quot;&gt;Login&lt;/div&gt;
                    &lt;div class=&quot;card-body&quot;&gt;
                        &lt;form action=&quot;{{ route('login.action') }}&quot; method=&quot;POST&quot;&gt;
                            @csrf
                            &lt;div class=&quot;form-group row&quot;&gt;
                                &lt;label for=&quot;email_address&quot; class=&quot;col-md-4 col-form-label text-md-right&quot;&gt;E-Mail Address&lt;/label&gt;
                                &lt;div class=&quot;col-md-6&quot;&gt;
                                    &lt;input type=&quot;text&quot; id=&quot;email_address&quot; class=&quot;form-control&quot; name=&quot;email&quot; required autofocus&gt;
                                    @if ($errors-&gt;has('email'))
                                    &lt;span class=&quot;text-danger&quot;&gt;{{ $errors-&gt;first('email') }}&lt;/span&gt;
                                    @endif
                                &lt;/div&gt;
                            &lt;/div&gt;
                            &lt;div class=&quot;form-group row&quot;&gt;
                                &lt;label for=&quot;password&quot; class=&quot;col-md-4 col-form-label text-md-right&quot;&gt;Password&lt;/label&gt;
                                &lt;div class=&quot;col-md-6&quot;&gt;
                                    &lt;input type=&quot;password&quot; id=&quot;password&quot; class=&quot;form-control&quot; name=&quot;password&quot; required&gt;
                                    @if ($errors-&gt;has('password'))
                                    &lt;span class=&quot;text-danger&quot;&gt;{{ $errors-&gt;first('password') }}&lt;/span&gt;
                                    @endif
                                &lt;/div&gt;
                            &lt;/div&gt;
                            &lt;div class=&quot;form-group row&quot;&gt;
                                &lt;div class=&quot;col-md-6 offset-md-4&quot;&gt;
                                    &lt;div class=&quot;checkbox&quot;&gt;
                                        &lt;label&gt;
                                            &lt;input type=&quot;checkbox&quot; name=&quot;remember&quot;&gt; Remember Me
                                        &lt;/label&gt;
                                    &lt;/div&gt;
                                &lt;/div&gt;
                            &lt;/div&gt;
                            &lt;div class=&quot;col-md-6 offset-md-4&quot;&gt;
                                &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;
                                    Login
                                &lt;/button&gt;
                                &lt;a href=&quot;{{ route('register') }}&quot; class=&quot;text-primary&quot; style=&quot;float: right;&quot;&gt;Register&lt;/a&gt;
                            &lt;/div&gt;
                        &lt;/form&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/main&gt;

@endsection</pre>

<div class="new-line-label"><strong>iii</strong> &#8211; Create(registration) a views file named registration.blade.php inside &#8220;resources\views\auth\&#8221; folder. </div>
<pre class="crayon-plain-tag">@extends('layout')

@section('content')

&lt;main class=&quot;flex-shrink-0&quot;&gt;
    &lt;div class=&quot;container mt-5&quot;&gt;
        &lt;div class=&quot;row justify-content-center&quot;&gt;
            &lt;div class=&quot;col-md-8&quot;&gt;
                &lt;h2 class=&quot;mt-5 text-center&quot;&gt;Laravel 9 Login and Registration&lt;/h2&gt;
                &lt;div class=&quot;card&quot;&gt;
                    &lt;div class=&quot;card-header&quot;&gt;Register&lt;/div&gt;
                    &lt;div class=&quot;card-body&quot;&gt;
                        &lt;form action=&quot;{{ route('register.action') }}&quot; method=&quot;POST&quot;&gt;
                            @csrf
                            &lt;div class=&quot;form-group row&quot;&gt;
                                &lt;label for=&quot;name&quot; class=&quot;col-md-4 col-form-label text-md-right&quot;&gt;Name&lt;/label&gt;
                                &lt;div class=&quot;col-md-6&quot;&gt;
                                    &lt;input type=&quot;text&quot; id=&quot;name&quot; class=&quot;form-control&quot; name=&quot;name&quot; required autofocus&gt;
                                    @if ($errors-&gt;has('name'))
                                    &lt;span class=&quot;text-danger&quot;&gt;{{ $errors-&gt;first('name') }}&lt;/span&gt;
                                    @endif
                                &lt;/div&gt;
                            &lt;/div&gt;
                            &lt;div class=&quot;form-group row&quot;&gt;
                                &lt;label for=&quot;email_address&quot; class=&quot;col-md-4 col-form-label text-md-right&quot;&gt;E-Mail Address&lt;/label&gt;
                                &lt;div class=&quot;col-md-6&quot;&gt;
                                    &lt;input type=&quot;text&quot; id=&quot;email_address&quot; class=&quot;form-control&quot; name=&quot;email&quot; required autofocus&gt;
                                    @if ($errors-&gt;has('email'))
                                    &lt;span class=&quot;text-danger&quot;&gt;{{ $errors-&gt;first('email') }}&lt;/span&gt;
                                    @endif
                                &lt;/div&gt;
                            &lt;/div&gt;
                            &lt;div class=&quot;form-group row&quot;&gt;
                                &lt;label for=&quot;password&quot; class=&quot;col-md-4 col-form-label text-md-right&quot;&gt;Password&lt;/label&gt;
                                &lt;div class=&quot;col-md-6&quot;&gt;
                                    &lt;input type=&quot;password&quot; id=&quot;password&quot; class=&quot;form-control&quot; name=&quot;password&quot; required&gt;
                                    @if ($errors-&gt;has('password'))
                                    &lt;span class=&quot;text-danger&quot;&gt;{{ $errors-&gt;first('password') }}&lt;/span&gt;
                                    @endif
                                &lt;/div&gt;
                            &lt;/div&gt;
                            &lt;div class=&quot;col-md-6 offset-md-4&quot;&gt;
                                &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;
                                    Register
                                &lt;/button&gt;
                                &lt;a href=&quot;{{ route('login') }}&quot; class=&quot;text-primary&quot; style=&quot;float: right;&quot;&gt;Login&lt;/a&gt;
                            &lt;/div&gt;
                        &lt;/form&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/main&gt;

@endsection</pre>

<div class="new-line-label"><strong>iv</strong> &#8211; Create(dashboard) a views file named dashboard.blade.php inside &#8220;resources\views\&#8221; folder. </div>
<pre class="crayon-plain-tag">@extends('layout')

@section('content')

&lt;main class=&quot;flex-shrink-0&quot;&gt;
    &lt;div class=&quot;container mt-5&quot;&gt;
        &lt;div class=&quot;row justify-content-center&quot;&gt;
            &lt;div class=&quot;col-md-8&quot;&gt;
                &lt;h2 class=&quot;mt-5 text-center&quot;&gt;Laravel 9 Login and Registration&lt;/h2&gt;
                &lt;div class=&quot;card&quot;&gt;
                    &lt;div class=&quot;card-header&quot;&gt;{{ __('Dashboard') }}&lt;/div&gt;
                    &lt;div class=&quot;card-body&quot;&gt;
                        @if (session('success'))
                        &lt;div class=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;
                            {{ session('success') }}
                        &lt;/div&gt;
                        @endif
                        You are Logged In
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/main&gt;

@endsection</pre>

<div class="new-line-bold">Step 6: Run Laravel Application: </div>
<div class="new-line-label">Finally, start the server. So, execute the PHP artisan serve command on the terminal:</div>
<pre class="crayon-plain-tag">php artisan serve
    If want to run the project different port to use the below command
    php artisan serve --port=9090</pre>

<div class="new-line-bold">Now, Go to your web browser, type the given URL:</div>
<pre class="crayon-plain-tag">http://localhost:8000/login</pre>

<div class="ex-read-more">
    <a href="https://techarise.com/codeigniter-authentication-login-registration/" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
            Also Read : Codeigniter 4 Authentication Login and Registration
        </div>
    </a>
</div>

<div class="new-line-label">
    <a class="btn btn-success" title="Demo" href="#" target="_balnk" rel="noopener noreferrer"><i class="fa fa-fw fa-eye"></i> Demo</a>

    <a class="btn btn-primary" title="Download" href="#" target="_balnk" rel="noopener noreferrer"><i class="fa fa-fw fa-download text-right"></i> Download</a>
</div><p>The post <a href="https://techarise.com/laravel-registration-login/">Laravel 9 Registration and Login using MySQL</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></content:encoded>
					
		
		
			<dc:creator>techariseinfo@gmail.com (TechArise Team)</dc:creator></item>
		<item>
		<title>Convert HTML Content to PDF using JavaScript</title>
		<link>https://techarise.com/convert-html-content-to-pdf-using-javascript/</link>
		
		
		<pubDate>Sun, 25 Dec 2022 11:54:46 +0000</pubDate>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">https://techarise.com/?p=1305</guid>

					<description><![CDATA[<p>PDF stands for the Portable Document Format. The PDF format is commonly used for saving documents and publications in a&#8230;</p>
<p>The post <a href="https://techarise.com/convert-html-content-to-pdf-using-javascript/">Convert HTML Content to PDF using JavaScript</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></description>
										<content:encoded><![CDATA[<div class="new-line-label">PDF stands for the Portable Document Format. The PDF format is commonly used for saving documents and publications in a standard format that can be viewed on multiple devices. For example, invoices, concert tickets, and flight tickets tend to be available as PDF downloads.</div>

<div class="new-line-label">In previous article, we have explained about how to <a href="https://techarise.com/create-pdf-file-using-codeigniter-with-mysql/" target="_blank" rel="noopener">Create PDF file using Codeigniter with MYSQL</a>. In this tutorial, I will explain you how to Convert HTML Content to PDF in JavaScript using jsPDF library.</div>

<div class="ex-read-more">
    <a href="https://techarise.com/password-protected-pdf-generation-in-php-mysql" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
            Also Read : Password Protected PDF Generation in PHP and MySQL
        </div>
    </a>
</div>

<div class="top-line-bold">Before starting to implement the Convert HTML Content to PDF using JavaScript, look files structure:</div>
<ul class="tree-structure">
    <li><i class="folder-color fa fa-folder"></i> html-pdf-javascript
        <ul>
            <li><i class="folder-color fa fa-folder"></i> css</li>
            <li><i class="folder-color fa fa-folder"></i> js
                <ul>
                    <li><i class="text-muted far fa-file"></i> jsPDF.js</li>
                </ul>
            </li>
            <li><i class="folder-color fa fa-folder"></i> templates
                <ul>
                    <li><i class="text-muted far fa-file"></i> header.php</li>
                    <li><i class="text-muted far fa-file"></i> footer.php</li>
                </ul>
            </li>
            <li><i class="text-muted far fa-file"></i> index.php</li>
            <li><i class="text-muted far fa-file"></i> menus.php.php</li>
        </ul>
    </li>
</ul>

<div class="new-line-bold">Step 1: Include jQuery, Bootstrap and jsPDF Library</div>
<div class="new-line-label">Include the jQuery and jsPDF library files to use the jsPDF class.</div>
<pre class="crayon-plain-tag">&lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css&quot;&gt;
    &lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js&quot;&gt;&lt;/script&gt;</pre>

<div class="new-line-label">Include jsPDF and html2canvas library.</div>
<pre class="crayon-plain-tag">&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.1/jspdf.umd.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.2.1/html2canvas.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;js/jsPDF.js&quot;&gt;&lt;/script&gt;</pre>


<div class="new-line-bold">Step 2: Create HTML Form</div>
<div class="new-line-label">Create a file named index.php, we will create HTML form with file input to browse HTML file to convert into PDF.</div>
<pre class="crayon-plain-tag">&lt;?php
include('templates/header.php');
?&gt;
&lt;main role=&quot;main&quot; class=&quot;container mcontainer&quot;&gt;
	&lt;div class=&quot;row home-sections&quot;&gt;
		&lt;h2 class=&quot;mt-5&quot;&gt;Convert HTML Content to PDF using JavaScript&lt;/h2&gt;
	&lt;/div&gt;

	&lt;div class=&quot;row&quot;&gt;
		&lt;div class=&quot;col-md-12&quot;&gt;
			&lt;form name=&quot;foo&quot; method=&quot;post&quot; class=&quot;input-form&quot; enctype=&quot;multipart/form-data&quot;&gt;
				&lt;div style=&quot;margin-bottom: 25px&quot; class=&quot;input-group&quot;&gt;
					&lt;div class=&quot;custom-file&quot;&gt;
						&lt;input type=&quot;file&quot; name=&quot;fileUpload&quot; class=&quot;custom-file-input&quot; id=&quot;file-upl&quot; required accept=&quot;.html,.htm&quot;&gt;
						&lt;label class=&quot;custom-file-label&quot; for=&quot;file-upl&quot;&gt;Choose file...&lt;/label&gt;
					&lt;/div&gt;
				&lt;/div&gt;
				&lt;div class=&quot;content-preview&quot;&gt;
					&lt;div id=&quot;previewHtmlContent&quot;&gt;&lt;/div&gt;
				&lt;/div&gt;
				&lt;div style=&quot;float: right;&quot;&gt;
					&lt;button type=&quot;button&quot; class=&quot;btn btn-info btn-sm&quot; id=&quot;previewHtml&quot;&gt;Preview&lt;/button&gt;
					&lt;span id=&quot;error-message&quot; class=&quot;error&quot;&gt;&lt;/span&gt;
					&lt;button type=&quot;button&quot; class=&quot;btn btn-success hidden btn-sm&quot; id=&quot;convertHTMLToPDF&quot;&gt;Create PDF&lt;/button&gt;
				&lt;/div&gt;
			&lt;/form&gt;
		&lt;/div&gt;
	&lt;/div&gt;
&lt;/main&gt;
&lt;?php include('templates/footer.php'); ?&gt;</pre>

<div class="new-line-bold">Step 3: Generate PDF using JavaScript</div>
<pre class="crayon-plain-tag">jQuery(document).ready(function() {
    // preview file
    jQuery(document).on('click', 'button#previewHtml', function() {
        previewHTMLFile();
    });
    // convert pdf file
    jQuery(document).on('click', 'button#convertHTMLToPDF', function() {
        saveHTMLToPDF();
    });
});

// upload pdf file and preview method
function previewHTMLFile() {
    var fileContents = '';
    jQuery(&quot;#error-message&quot;).html(&quot;&quot;);
    var uplfilePath = jQuery('input#file-upl').get(0).files[0];

    if (jQuery(uplfilePath).length != 0) {
        var filereader = new FileReader();
        filereader.onload = function(e) {
            fileContents = e.target.result;
            jQuery(&quot;.content-preview&quot;).show();
            jQuery(&quot;#previewHtmlContent&quot;).html(fileContents);
            jQuery(&quot;#previewHtml&quot;).addClass('hidden');
            jQuery(&quot;#convertHTMLToPDF&quot;).removeClass('hidden');
        }
        filereader.readAsText(uplfilePath);
    } else {
        jQuery(&quot;#error-message&quot;).html(&quot;Please choose file.&quot;).show();
    }
}

// generate pdf file
function saveHTMLToPDF() {
    const { jsPDF } = window.jspdf;
    var doc = new jsPDF('l', 'mm', [1200, 1210]);
    var pdfJS = document.querySelector('#previewHtmlContent');
    doc.html(pdfJS, {
        callback: function(doc) {
            // Save the PDF
            doc.save(&quot;sample-document.pdf&quot;);
        },
        x: 10,
        y: 10
    });
}</pre>

<div class="new-line-bold">Step 4: Upload file and Preview HTML</div>
<div class="new-line-label">call function previewHTMLFile() to show HTML file preview.</div>
<pre class="crayon-plain-tag">// preview file
    jQuery(document).on('click', 'button#previewHtml', function() {
        previewHTMLFile();
    });</pre>
<div class="new-line-label">Create function previewHTMLFile() to upload html file and preview</div>
<pre class="crayon-plain-tag">// upload html file and preview
    function previewHTMLFile() {
        var fileContents = '';
        jQuery(&quot;#error-message&quot;).html(&quot;&quot;);
        var uplfilePath = jQuery('input#file-upl').get(0).files[0];

        if (jQuery(uplfilePath).length != 0) {
            var filereader = new FileReader();
            filereader.onload = function(e) {
                fileContents = e.target.result;
                jQuery(&quot;.content-preview&quot;).show();
                jQuery(&quot;#previewHtmlContent&quot;).html(fileContents);
                jQuery(&quot;#previewHtml&quot;).addClass('hidden');
                jQuery(&quot;#convertHTMLToPDF&quot;).removeClass('hidden');
            }
            filereader.readAsText(uplfilePath);
        } else {
            jQuery(&quot;#error-message&quot;).html(&quot;Please choose file.&quot;).show();
        }
    }</pre>

<div class="new-line-bold">Step 5: Convert HTML File to PDF</div>
<div class="new-line-label">call function saveHTMLToPDF() to convert HTML to PDF, save and download</div>
<pre class="crayon-plain-tag">// convert pdf file
    jQuery(document).on('click', 'button#convertHTMLToPDF', function() {
        saveHTMLToPDF();
    });</pre>
<div class="new-line-label">We will implement function saveHTMLToPDF() to get HTML file content and convert to PDF using function html() from jsPDF. The function save() called from jsPDF to dwonload output PDF file.</div>
<pre class="crayon-plain-tag">// generate pdf file and save
function saveHTMLToPDF() {
    const { jsPDF } = window.jspdf;
    var doc = new jsPDF('l', 'mm', [1200, 1210]);
    var pdfJS = document.querySelector('#previewHtmlContent');
    doc.html(pdfJS, {
        callback: function(doc) {
            // Save the PDF
            doc.save(&quot;sample-document.pdf&quot;);
        },
        x: 10,
        y: 10
    });
}</pre>

<div class="new-line-bold">Create files named (header.php and footer.php)</div>
<div class="new-line-label">This file contains the header and footer section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.
</div>
<div class="new-line-bold">header.php</div>
<pre class="crayon-plain-tag">&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;meta name=&quot;google-site-verification&quot; content=&quot;jlByZLO42gqjZgfAEj29-VYfJC2hEwUj1KSeQpiGJcI&quot; /&gt;
		&lt;link rel=&quot;canonical&quot; href=&quot;https://techarise.com/&quot; /&gt;
		&lt;meta name=&quot;author&quot; content=&quot;TechArise&quot;&gt;
		&lt;meta name=&quot;description&quot; content=&quot;Learn Web Development Tutorials &amp; Web Developer Resources, PHP, MySQL, jQuery, CSS, XHTML, jQuery UI, CSS3, HTML5, HTML, web design, webdesign, with TechArise tutorials. View live demo&quot;&gt;
		&lt;meta name=&quot;keywords&quot; content=&quot;TechArise, tutorial TechArise, tutorials, freebies, resources, web development, webdev, demo, PHP, MySQL, jQuery, CSS, XHTML, jQuery UI, CSS3, HTML5, HTML, web design, webdesign, php script, dynamic web content&quot; /&gt;
		&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
    &lt;link rel=&quot;icon&quot; type=&quot;image/ico&quot; href=&quot;https://techarise.com/wp-content/themes/v1/favicon.ico&quot;&gt;
    &lt;!-- Bootstrap CSS --&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css&quot;&gt;
    &lt;link href=&quot;http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css&quot; rel=&quot;stylesheet&quot;&gt;
		&lt;link rel=&quot;stylesheet&quot; href=&quot;css/style.css&quot; /&gt;
		&lt;title&gt; Convert HTML Content to PDF using JavaScript | Tech Arise&lt;/title&gt; 

  &lt;/head&gt;
  &lt;body&gt;
&lt;?php include('menus.php'); ?&gt;</pre>

<div class="new-line-bold">menus.php</div>
<pre class="crayon-plain-tag">&lt;header&gt;
  &lt;!-- Fixed navbar --&gt;
  &lt;nav class=&quot;navbar navbar-expand-md navbar-dark fixed-top bg-dark&quot; style=&quot;background: #273E4A!important;&quot;&gt;
    &lt;a class=&quot;navbar-brand&quot; href=&quot;https://techarise.com&quot;&gt;&lt;strong&gt;Tech Arise&lt;/strong&gt;&lt;/a&gt;
    &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navbarCollapse&quot; aria-controls=&quot;navbarCollapse&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation&quot;&gt;
      &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;
    &lt;/button&gt;
    &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarCollapse&quot;&gt;
      &lt;ul class=&quot;navbar-nav mr-auto&quot;&gt;
        &lt;li class=&quot;nav-item active&quot;&gt;
          &lt;a class=&quot;nav-link&quot; href=&quot;https://techarise.com&quot;&gt;Home &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;&lt;/a&gt;
        &lt;/li&gt;
      &lt;/ul&gt;
      &lt;span class=&quot;nav-item dropdown&quot;&gt;
        &lt;a style=&quot;color:#fff;&quot; class=&quot;nav-link&quot; href=&quot;index.php&quot; id=&quot;navbarDropdown&quot; role=&quot;button&quot; data-toggle=&quot;dropdown&quot; aria-haspopup=&quot;true&quot; aria-expanded=&quot;false&quot;&gt;
          &lt;i class=&quot;fa fa-user&quot; style=&quot;width:20px;&quot;&gt;&lt;/i&gt; Demo
        &lt;/a&gt;
      &lt;/span&gt;
    &lt;/div&gt;
  &lt;/nav&gt;
&lt;/header&gt;</pre>
<div class="new-line-bold">footer.php</div>
<pre class="crayon-plain-tag">&lt;footer class=&quot;footer&quot;&gt;
  &lt;div class=&quot;container&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;/footer&gt;
&lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.1/jspdf.umd.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.2.1/html2canvas.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/jsPDF.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;

&lt;/html&gt;</pre>

<div class="ex-read-more new-line-label">
    <a href="https://techarise.com/restful-api-using-python-mysql" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
            Also Read : Build Simple RESTful API using Python and MySQL
        </div>
    </a>
</div>

<div class="new-line-label">
    <a class="btn btn-primary" title="Demo" href="" target="_blank" rel="noopener noreferrer"><i class="fa fa-fw fa-eye"></i> Demo</a>

    <a class="btn btn-info" title="Download" href="" target="_blank" rel="noopener noreferrer"><i class="fa fa-fw fa-download text-right"></i> Download</a>
</div><p>The post <a href="https://techarise.com/convert-html-content-to-pdf-using-javascript/">Convert HTML Content to PDF using JavaScript</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></content:encoded>
					
		
		
			<dc:creator>techariseinfo@gmail.com (TechArise Team)</dc:creator></item>
		<item>
		<title>Create Simple Pagination Using PHP and MySQL</title>
		<link>https://techarise.com/pagination-php-mysql/</link>
		
		
		<pubDate>Sun, 18 Dec 2022 13:30:35 +0000</pubDate>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">https://techarise.com/?p=1418</guid>

					<description><![CDATA[<p>Pagination is one of the most frequently used features for web applications. Pagination is the process of dividing a document&#8230;</p>
<p>The post <a href="https://techarise.com/pagination-php-mysql/">Create Simple Pagination Using PHP and MySQL</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></description>
										<content:encoded><![CDATA[<div class="new-line-label">Pagination is one of the most frequently used features for web applications. Pagination is the process of dividing a document into discrete pages. Paging allows you to display all of your retrieved results on multiple pages rather than all of them on a single page. So We have shared in this tutorial, we will learn how to Build a pagination PHP &#038; MySQL pagination and enhance it further as per our needs.</div>

<div class="ex-read-more">
    <a href="https://techarise.com/ajax-pagination-using-codeigniter-mysql/" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
           Also Read: Simple Pagination Using CodeIgniter and MySQL
        </div>  
    </a>
</div>

<div class="top-line-bold">Before starting to implement the Simple Pagination Using PHP and MySQL, look files structure:</div>
<ul class="tree-structure"> 
  <li><i class="folder-color fa fa-folder"></i> pagination-php-mysql
  <ul>
  <li><i class="folder-color fa fa-folder"></i> class
      <ul>
          <li><i class="text-muted far fa-file"></i> DBConnection.php</li>
          <li><i class="text-muted far fa-file"></i> Employee.php</li>
      </ul>      
    </li>
    <li><i class="folder-color fa fa-folder"></i> templates
      <ul>
          <li><i class="text-muted far fa-file"></i> header.php</li>
          <li><i class="text-muted far fa-file"></i> footer.php</li>
      </ul>      
    </li>  
    <li><i class="text-muted far fa-file"></i> index.php</li>
  </ul>
</li>
</ul>


<div class="new-line-bold">Step 1: Create the database and Table</div>
<div class="new-line-label">For this tutorial, you need a MySQL database with the following table: </div>
<pre class="crayon-plain-tag">//Table structure for table `employee`
   CREATE TABLE `employee` (
    `id` int(11) NOT NULL,
    `name` varchar(255) NOT NULL,
    `email` varchar(255) DEFAULT NULL,
    `gender` varchar(11) NOT NULL,
    `address` varchar(255) NOT NULL
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

  ALTER TABLE `employee`
    ADD PRIMARY KEY (`id`);

  ALTER TABLE `employee`
      MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;

//Dumping data for table `employee`

INSERT INTO `employee` (`id`, `name`, `email`, `gender`, `address`) VALUES
(1, 'Adam', 'adam@techarisel.com', 'Male', 'New York'),
(2, 'Admin', 'admin@techarisel.com', 'Male', 'Boston'),
(3, 'User', 'user@techarisel.com', 'Male', 'California'),
(4, 'Author', 'author@techarisel.com', 'Male', 'Washington '),
(5, 'Sam', 'sam@techarisel.com', 'Male', 'Delhi'),
(6, 'James', 'james@techarisel.com', 'Male', 'Chennai'),
(7, 'Jakey', 'jakey@techarisel.com', 'Male', 'Mumbai'),
(8, 'Harry', 'harry@techarisel.com', 'Male', 'Kolkata'),
(9, 'John', 'john@techarisel.com', 'Male', 'Lucknow'),
(10, 'Lily', 'lily@techarisel.com', 'Female', 'Landon'),
(11, 'Smith', 'smith@techarisel.com', 'Male', 'New York'),
(12, 'Jacab', 'jacab@techarisel.com', 'Male', 'California'),
(13, 'Joseph', 'joseph@techarisel.com', 'Male', 'Washington '),
(14, 'Jolly', 'jolly@techarisel.com', 'Male', 'Delhi');</pre>

<div class="new-line-bold">Step 2: Database Connection/Config class</div>
<div class="new-line-label">Create a file named DBConnection.php inside “class/” folder.</div>
<pre class="crayon-plain-tag">&lt;?php
/**
 * @package DBConnection
 *
 * @author TechArise Team
 *
 * @email  info@techarise.com
 *   
 */

// Database Connection
class DBConnection {
    private $_dbHostname = &quot;localhost&quot;;
    private $_dbName = &quot;techarise_DB&quot;;
    private $_dbUsername = &quot;root&quot;;
    private $_dbPassword = &quot;&quot;;
    private $_con;

    public function __construct() {
      try {
          $this-&gt;_con = new PDO(&quot;mysql:host=$this-&gt;_dbHostname;dbname=$this-&gt;_dbName&quot;, $this-&gt;_dbUsername, $this-&gt;_dbPassword);    
          $this-&gt;_con-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      } catch(PDOException $e) {
      echo &quot;Connection failed: &quot; . $e-&gt;getMessage();
    }

    }
    // return Connection
    public function returnConnection() {
        return $this-&gt;_con;
    }
}

?&gt;</pre>

<div class="new-line-bold">Step 3: Create a class file</div>
<div class="new-line-label">Create a class file named Employee.php inside “class/” folder.</div>
<ul style="padding-left: 30px;">
  <li><strong>The class handles the Employee process.</strong></li>
  <li><code>__construct()</code> – Loads the required class.</li>
  <li><code>getAllEmployee()</code> – list all recoreds from database</li>
  <li><code>countEmployee()</code> – count emp records from database</li>
</ul>
<pre class="crayon-plain-tag">&lt;?php
/**
 * @package Employee class
 *
 * @author TechArise Team
 *
 * @email  info@techarise.com
 *   
 */

// include connection class
include(&quot;DBConnection.php&quot;);
// Employee
class Employee 
{
    protected $db;
    private $_page;
    private $_rowPerPage;
    private $_start;

    public function setPage($page) {
        $this-&gt;_page = $page;
    }

    public function setRowPerPage($rowPerPage) {
        $this-&gt;_rowPerPage = $rowPerPage;
    }
    public function setStart($start) {
        $this-&gt;_start = $start;
    }
    public function setStatus($status) {
        $this-&gt;_status = $status;
    }
    
    // __construct
    public function __construct() {
        $this-&gt;db = new DBConnection();
        $this-&gt;db = $this-&gt;db-&gt;returnConnection();
    }

    // getAll Employee
    public function getAllEmployee() {
      try {
        $sql = &quot;SELECT * FROM employee &quot;;
            $limit=&quot; limit &quot; . $this-&gt;_start . &quot;,&quot; . $this-&gt;_rowPerPage;
            $query = $sql.$limit;
        $stmt = $this-&gt;db-&gt;prepare($query);
        
        $stmt-&gt;execute();
        $result = $stmt-&gt;fetchAll(\PDO::FETCH_ASSOC);
            return $result;
    } catch (Exception $err) {
        die(&quot;Oh noes! There's an error in the query! &quot; . $err);
    }
    }
    // count Employee
    public function countEmployee() {
      try {
        $sql = &quot;SELECT * FROM employee&quot;;
        $stmt = $this-&gt;db-&gt;prepare($sql);
        $stmt-&gt;execute();
        $count = $stmt-&gt;rowCount();
            return $count;
    } catch (Exception $err) {
        die(&quot;Oh noes! There's an error in the query! &quot; . $err);
    }
    }

}

?&gt;</pre>

<div class="new-line-bold">Step 4: Create HTML file named index.php </div>
<pre class="crayon-plain-tag">&lt;?php
include_once 'class/Employee.php';
// Number of entries to show in a page.
define(&quot;ROW_PER_PAGE&quot;, 5);
$page = 1;
$start = 0;
// Look for a GET variable page if not found default is 1.
if (!empty($_GET[&quot;page&quot;])) {
  $page = $_GET[&quot;page&quot;];
  $start = ($page - 1) * ROW_PER_PAGE;
}
$emp = new Employee();
$emp-&gt;setRowPerPage(ROW_PER_PAGE);
$emp-&gt;setStart($start);
$emp-&gt;setPage($page);
$empInfo = $emp-&gt;getAllEmployee();
$rowCount = $emp-&gt;countEmployee();
include('templates/header.php');
$per_page_html = '';
?&gt;
&lt;section class=&quot;showcase&quot;&gt;
  &lt;div class=&quot;container&quot;&gt;
    &lt;div class=&quot;pb-2 mt-4 mb-2 border-bottom&quot;&gt;
      &lt;h2 class=&quot;text-center&quot;&gt;Simple Pagination Using PHP and MySQL&lt;/h2&gt;
    &lt;/div&gt;
    &lt;div class=&quot;page-content page-container&quot; id=&quot;page-content&quot;&gt;
      &lt;div class=&quot;padding&quot;&gt;
        &lt;div class=&quot;row container d-flex justify-content-center&quot;&gt;
          &lt;div class=&quot;col-lg-12&quot;&gt;
            &lt;div class=&quot;card px-3&quot;&gt;
              &lt;div class=&quot;card-body&quot;&gt;
                &lt;div class=&quot;list-wrapper&quot;&gt;
                  &lt;table class=&quot;table table-striped&quot;&gt;
                    &lt;thead&gt;
                      &lt;tr&gt;
                        &lt;th style=&quot;width: 20%;&quot;&gt;Name&lt;/th&gt;
                        &lt;th style=&quot;width: 30%;&quot;&gt;Email&lt;/th&gt;
                        &lt;th style=&quot;width: 20%;&quot;&gt;Gender&lt;/th&gt;
                        &lt;th style=&quot;width: 30%;&quot;&gt;Address&lt;/th&gt;
                      &lt;/tr&gt;
                    &lt;/thead&gt;
                    &lt;tbody&gt;
                      &lt;?php
                      // Showing the Records
                      foreach ($empInfo as $key =&gt; $element) { ?&gt;
                        &lt;tr&gt;
                          &lt;td&gt;&lt;?php echo $element['name']; ?&gt;&lt;/td&gt;
                          &lt;td&gt;&lt;?php echo $element['email']; ?&gt;&lt;/td&gt;
                          &lt;td&gt;&lt;?php echo $element['gender']; ?&gt;&lt;/td&gt;
                          &lt;td&gt;&lt;?php echo $element['address']; ?&gt;&lt;/td&gt;
                        &lt;/tr&gt;
                      &lt;?php } ?&gt;
                    &lt;/tbody&gt;
                  &lt;/table&gt;
                  &lt;?php
                  //Showing the Page Navigation
                  if (!empty($rowCount)) {
                    $per_page_html .= '&lt;ul class=&quot;pagination float-right&quot;&gt;';
                    $page_count = ceil($rowCount / ROW_PER_PAGE);
                    if ($page_count &gt; 1) {
                      for ($i = 1; $i &lt;= $page_count; $i++) {
                        if ($i == $page) {
                          $per_page_html .= '&lt;li class=&quot;page-item active&quot;&gt;&lt;a class=&quot;page-link&quot; href=&quot;?page=' . $i . '&quot;&gt;' . $i . '&lt;/a&gt;&lt;/li&gt;';
                        } else {
                          $per_page_html .= '&lt;li class=&quot;page-item&quot;&gt;&lt;a class=&quot;page-link&quot; href=&quot;?page=' . $i . '&quot;&gt;' . $i . '&lt;/a&gt;&lt;/li&gt;';
                        }
                      }
                    }
                    $per_page_html .= &quot;&lt;/ul&gt;&quot;;
                  }
                  echo $per_page_html;
                  ?&gt;

                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/section&gt;
&lt;?php include('templates/footer.php'); ?&gt;
?&gt;</pre>

<div class="new-line-bold">Step 5:Create a view(header) </div>
<div class="new-line-label">Create a view file named header.php inside “templates” folder. </div>
<div class="new-line-label">This view contains the header section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header section. </div>
<pre class="crayon-plain-tag">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;

&lt;head&gt;
  &lt;meta charset=&quot;utf-8&quot;&gt;
  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
  &lt;meta name=&quot;description&quot; content=&quot;&quot;&gt;
  &lt;meta name=&quot;author&quot; content=&quot;&quot;&gt;

  &lt;title&gt;Simple Pagination Using PHP and MySQL | Tech Arise&lt;/title&gt;
  &lt;!-- Bootstrap core CSS --&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css&quot; /&gt;
  &lt;!-- Custom fonts for this template --&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css&quot; /&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css&quot; /&gt;
  &lt;link href=&quot;https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;
  &lt;!-- Custom styles for this template --&gt;
  &lt;link href=&quot;css/style.css&quot; rel=&quot;stylesheet&quot;&gt;
&lt;/head&gt;

&lt;body&gt;
  &lt;!-- Navigation --&gt;
  &lt;nav class=&quot;navbar navbar-expand-lg navbar-dark bg-dark static-top header-bg-dark&quot; style=&quot;background: #FFFFFF;&quot;&gt;
    &lt;div class=&quot;container&quot;&gt;
      &lt;a class=&quot;navbar-brand font-weight-bold&quot; href=&quot;https://techarise.com&quot;&gt;
        &lt;h1&gt;Tech Arise&lt;/h1&gt;
      &lt;/a&gt;
      &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navbarResponsive&quot; aria-controls=&quot;navbarResponsive&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation&quot;&gt;
        &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;
      &lt;/button&gt;
      &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarResponsive&quot;&gt;
        &lt;ul class=&quot;navbar-nav ml-auto&quot;&gt;
          &lt;li class=&quot;nav-item active&quot;&gt;
            &lt;a class=&quot;nav-link&quot; href=&quot;https://techarise.com&quot;&gt;Home
              &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;
            &lt;/a&gt;
          &lt;/li&gt;
          &lt;li class=&quot;nav-item&quot;&gt;
            &lt;a class=&quot;nav-link&quot; href=&quot;https://techarise.com/php-free-script-demos/&quot;&gt;Live Demo&lt;/a&gt;
          &lt;/li&gt;
        &lt;/ul&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/nav&gt;</pre>

<div class="new-line-bold">Step 6: Create a view(footer) </div>
<div class="new-line-label">Create a view file named footer.php inside “templates” folder. </div>
<div class="new-line-label">This view contains the footer section of the webpage. </div>
<pre class="crayon-plain-tag">&lt;!-- Footer --&gt;
&lt;footer class=&quot;footer bg-light footer-bg-dark&quot;&gt;
  &lt;div class=&quot;container&quot;&gt;
    &lt;div class=&quot;row&quot;&gt;
      &lt;div class=&quot;col-lg-6 h-100 text-center text-lg-left my-auto&quot;&gt;
        &lt;ul class=&quot;list-inline mb-2&quot;&gt;
          &lt;li class=&quot;list-inline-item&quot;&gt;
            &lt;a href=&quot;#&quot;&gt;About&lt;/a&gt;
          &lt;/li&gt;
          &lt;li class=&quot;list-inline-item&quot;&gt;&amp;sdot;&lt;/li&gt;
          &lt;li class=&quot;list-inline-item&quot;&gt;
            &lt;a href=&quot;#&quot;&gt;Contact&lt;/a&gt;
          &lt;/li&gt;
          &lt;li class=&quot;list-inline-item&quot;&gt;&amp;sdot;&lt;/li&gt;
          &lt;li class=&quot;list-inline-item&quot;&gt;
            &lt;a href=&quot;#&quot;&gt;Terms of Use&lt;/a&gt;
          &lt;/li&gt;
          &lt;li class=&quot;list-inline-item&quot;&gt;&amp;sdot;&lt;/li&gt;
          &lt;li class=&quot;list-inline-item&quot;&gt;
            &lt;a href=&quot;#&quot;&gt;Privacy Policy&lt;/a&gt;
          &lt;/li&gt;
        &lt;/ul&gt;
        &lt;p class=&quot;text-muted small mb-4 mb-lg-0&quot;&gt;Copyright &amp;copy; 2011 - &lt;?php print date('Y', time()); ?&gt; &lt;a href=&quot;https://techarise.com/&quot;&gt;TECHARISE.COM&lt;/a&gt; All rights reserved.&lt;/p&gt;
      &lt;/div&gt;
      &lt;div class=&quot;col-lg-6 h-100 text-center text-lg-right my-auto&quot;&gt;
        &lt;ul class=&quot;list-inline mb-0&quot;&gt;
          &lt;li class=&quot;list-inline-item mr-3&quot;&gt;
            &lt;a href=&quot;#&quot;&gt;
              &lt;i class=&quot;fab fa-facebook fa-2x fa-fw&quot;&gt;&lt;/i&gt;
            &lt;/a&gt;
          &lt;/li&gt;
          &lt;li class=&quot;list-inline-item mr-3&quot;&gt;
            &lt;a href=&quot;#&quot;&gt;
              &lt;i class=&quot;fab fa-twitter-square fa-2x fa-fw&quot;&gt;&lt;/i&gt;
            &lt;/a&gt;
          &lt;/li&gt;
          &lt;li class=&quot;list-inline-item&quot;&gt;
            &lt;a href=&quot;#&quot;&gt;
              &lt;i class=&quot;fab fa-instagram fa-2x fa-fw&quot;&gt;&lt;/i&gt;
            &lt;/a&gt;
          &lt;/li&gt;
        &lt;/ul&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/footer&gt;
&lt;!-- Bootstrap core JavaScript --&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;

&lt;/html&gt;</pre>

<div class="ex-read-more">
    <a href="https://techarise.com/ajax-pagination-using-codeigniter-mysql" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
           Also Read : Ajax Pagination Using CodeIgniter and MySQL
        </div>  
    </a>
</div>

<div class="new-line-label">
    <a class="btn btn-success" title="Demo" href="#" target="_balnk" rel="noopener noreferrer"><i class="fa fa-fw fa-eye"></i> Demo</a>  

   <a class="btn btn-primary" title="Download" href="#" target="_balnk" rel="noopener noreferrer"><i class="fa fa-fw fa-download text-right"></i> Download</a>
</div><p>The post <a href="https://techarise.com/pagination-php-mysql/">Create Simple Pagination Using PHP and MySQL</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></content:encoded>
					
		
		
			<dc:creator>techariseinfo@gmail.com (TechArise Team)</dc:creator></item>
		<item>
		<title>How to Print Page Area using JavaScript</title>
		<link>https://techarise.com/how-to-print-page-area-using-javascript/</link>
		
		
		<pubDate>Sun, 09 Oct 2022 16:16:21 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">https://techarise.com/?p=1414</guid>

					<description><![CDATA[<p>Page print in JavaScript is a simple code in JavaScript used to print the content of web pages. In this&#8230;</p>
<p>The post <a href="https://techarise.com/how-to-print-page-area-using-javascript/">How to Print Page Area using JavaScript</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></description>
										<content:encoded><![CDATA[<div class="new-line-label">Page print in JavaScript is a simple code in JavaScript used to print the content of web pages. In this article, we will share with you a simple way to print specific div content or full-page content using JavaScript. Here we will create a JavaScript function to print div content, page area, and full web page content. </div>

<div class="new-line-label">printPage() function contains some JavaScript code that helps you to implement the print feature easily on the web page. This is a very simple example, you can copy-paste, and change it according to your requirement.</div>


<div class="new-line-bold">JavaScript Code:</div>
<div class="new-line-label">You can use this function for print a web page content:</div>
<pre class="crayon-plain-tag">function printPage(selector, title) {
        var disp_setting=&quot;toolbar=yes,location=no,&quot;;
        disp_setting+=&quot;directories=yes,menubar=yes,&quot;;
        disp_setting+=&quot;scrollbars=yes,width=1024, height=700, left=100, top=25&quot;;
        var content_vlue = document.getElementById(selector).innerHTML;
        var print=window.open(&quot;&quot;,&quot;&quot;, disp_setting);
        print.document.open();
        print.document.write('&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot;');
        print.document.write('&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;');
        print.document.write('&lt;html&gt;');
        print.document.write('&lt;head&gt;&lt;title&gt;'+title+'&lt;/title&gt;');
        print.document.write('&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;print_stylesheet.css&quot; /&gt;');
        print.document.write('&lt;/head&gt;&lt;body class=&quot;A4&quot;&gt;&lt;center&gt;');
        print.document.write(content_vlue);
        print.document.write('&lt;/center&gt;&lt;/body&gt;&lt;/html&gt;');
        setTimeout(function(){
            print.print();
            print.close();
        },500);
        
        print.focus();
    }</pre>

<div class="new-line-label">Use printPage() function on onclick event of print button element and provide the content area div ID which you want to print.</div>
<pre class="crayon-plain-tag">printPage('element_id', 'page_title')</pre>

<div class="new-line-bold">Trigger function &#8211; HTML Code:</div>
<pre class="crayon-plain-tag">&lt;button type=&quot;button&quot; name=&quot;print_btn&quot; class=&quot;btn btn-primary&quot; value=&quot;How to Print Page Area using JavaScript&quot; onclick=&quot;printPage('print-page', 'Print Page Area using JavaScript')&quot;&gt;Print Page&lt;/button&gt;</pre>

<div class="new-line-bold">HTML content that you want print</div>
<pre class="crayon-plain-tag">&lt;section class=&quot;sheet padding-5mm A4&quot; id=&quot;print-page&quot; style=&quot;display:none;&quot;&gt;
        Lorem Ipsum is simply dummy text of the printing and typesetting industry
    &lt;/section&gt;</pre>


<div class="new-line-bold">Finally Complete Code: </div>
<pre class="crayon-plain-tag">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;

&lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;title&gt;How to Print Page Area using JavaScript - TechArise&lt;/title&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        function printPage(selector, title) {
            var disp_setting=&quot;toolbar=yes,location=no,&quot;;
            disp_setting+=&quot;directories=yes,menubar=yes,&quot;;
            disp_setting+=&quot;scrollbars=yes,width=1024, height=700, left=100, top=25&quot;;
            var content_vlue = document.getElementById(selector).innerHTML;
            var print=window.open(&quot;&quot;,&quot;&quot;, disp_setting);
            print.document.open();
            print.document.write('&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot;');
            print.document.write('&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;');
            print.document.write('&lt;html&gt;');
            print.document.write('&lt;head&gt;&lt;title&gt;'+title+'&lt;/title&gt;');
            print.document.write('&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;print_stylesheet.css&quot; /&gt;');
            print.document.write('&lt;/head&gt;&lt;body class=&quot;A4&quot;&gt;&lt;center&gt;');
            print.document.write(content_vlue);
            print.document.write('&lt;/center&gt;&lt;/body&gt;&lt;/html&gt;');
            setTimeout(function(){
                print.print();
                print.close();
            },500);
            
            print.focus();
        }
    &lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;
	&lt;button type=&quot;button&quot; name=&quot;print_btn&quot; class=&quot;btn btn-primary&quot; value=&quot;How to Print Page Area using JavaScript&quot; onclick=&quot;printPage('print-page', 'Print Page Area using JavaScript')&quot;&gt;Print Page&lt;/button&gt;
    &lt;section class=&quot;sheet padding-5mm A4&quot; id=&quot;print-page&quot; style=&quot;display:none;&quot;&gt;
        &lt;article&gt;
            &lt;table width=&quot;98%&quot; class=&quot;w-100&quot;&gt;
                &lt;thead&gt;
                    &lt;tr&gt;
                        &lt;td class=&quot;text-center p-0 m-0&quot; colspan=&quot;2&quot;&gt;
                            &lt;h2 class=&quot;m-0 text-bold&quot;&gt;How to Print Page Area using JavaScript&lt;/h2&gt;
                        &lt;/td&gt;
                    &lt;/tr&gt;
                &lt;/thead&gt;
                &lt;tbody&gt;
                    &lt;td class=&quot; p-0&quot; colspan=&quot;2&quot;&gt;
                        &lt;br /&gt;
                    &lt;table class=&quot;tableBorderAll&quot;&gt;
                    &lt;tr&gt;
                        &lt;td class=&quot;text-bold&quot; style=&quot;width: 33%;text-transform: uppercase;text-align: center;&quot;&gt;Name&lt;/td&gt;
                        &lt;td class=&quot;text-bold p-0 pr-15&quot; style=&quot;width: 33%;&quot;&gt;Team TechArise&lt;/td&gt;
            			&lt;td class=&quot;text-bold&quot; style=&quot;width: 34%;&quot;&gt;Avatar&lt;/td&gt;
                    &lt;/tr&gt;
                    &lt;tr&gt;
                        &lt;td class=&quot;text-bold&quot; style=&quot;text-transform: uppercase;&quot;&gt;Email&lt;/td&gt;
                        &lt;td class=&quot;text-bold p-0 pr-15&quot;&gt;info@techarise.com&lt;/td&gt;
                        &lt;td rowspan=&quot;7&quot; class=&quot;text-bold&quot;&gt;
                            &lt;img src=&quot;User-Icon-File.png&quot; style=&quot;width:100%;padding:5px;&quot;&gt;
                    &lt;/tr&gt;
                    &lt;tr&gt;
                        &lt;td class=&quot;text-bold&quot; style=&quot;text-transform: uppercase;&quot;&gt;Mobile&lt;/td&gt;
                        &lt;td class=&quot;text-bold p-0 pr-15&quot;&gt;9000000001&lt;/td&gt;
                    &lt;/tr&gt;
                    &lt;tr&gt;
                        &lt;td class=&quot;text-bold&quot; style=&quot;text-transform: uppercase;&quot;&gt;Address&lt;/td&gt;
                        &lt;td class=&quot;text-bold p-0 pr-15&quot;&gt;B 45/90, San Francisco&lt;/td&gt;
                    &lt;/tr&gt;
                    &lt;tr&gt;
                        &lt;td class=&quot;text-bold&quot; style=&quot;text-transform: uppercase;&quot;&gt;Country&lt;/td&gt;
                        &lt;td class=&quot;text-bold p-0 pr-15&quot;&gt;United States&lt;/td&gt;
                    &lt;/tr&gt;
                    &lt;tr&gt;
                        &lt;td class=&quot;text-bold&quot; style=&quot;text-transform: uppercase;&quot;&gt;Salary&lt;/td&gt;
                        &lt;td class=&quot;text-bold p-0 pr-15&quot;&gt;$12000&lt;/td&gt;
                    &lt;/tr&gt;
                    &lt;tr&gt;
                        &lt;td class=&quot;text-bold&quot; style=&quot;text-transform: uppercase;&quot;&gt;Department&lt;/td&gt;
                        &lt;td class=&quot;text-bold p-0 pr-15&quot;&gt;Information technology (IT)&lt;/td&gt;
                    &lt;/tr&gt;
                    
                    &lt;/table&gt;
                    &lt;br&gt;
                    &lt;/td&gt;
                &lt;/tbody&gt;
            &lt;/table&gt;
        &lt;/article&gt;
    &lt;/section&gt;
&lt;/body&gt;

&lt;/html&gt;</pre><p>The post <a href="https://techarise.com/how-to-print-page-area-using-javascript/">How to Print Page Area using JavaScript</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></content:encoded>
					
		
		
			<dc:creator>techariseinfo@gmail.com (TechArise Team)</dc:creator></item>
		<item>
		<title>Read and Write JSON to File in Python</title>
		<link>https://techarise.com/read-write-to-json-file-in-python/</link>
		
		
		<pubDate>Sun, 15 May 2022 05:52:35 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">https://techarise.com/?p=1408</guid>

					<description><![CDATA[<p>In this tutorial, we will share with you how to Read and Write JSON to File using Python.JSON is commonly&#8230;</p>
<p>The post <a href="https://techarise.com/read-write-to-json-file-in-python/">Read and Write JSON to File in Python</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></description>
										<content:encoded><![CDATA[<div class="new-line-label">In this tutorial, we will share with you how to Read and Write JSON to File using Python.JSON is commonly used by web applications to transfer data between client and server.</div>

<div class="new-line-label">JSON (JavaScript Object Notation) is an easy-to-read format for interchange data. It is the text form of a javascript object. The key is of type “string “with double quotation marks and values can be string, number, or nested JSON. Python has a built-in JSON module that accept a JSON string and convert into a dictionary.</div>
<div class="ex-read-more new-line-label">
    <a href="https://techarise.com/import-csv-file-into-mongodb-using-python/" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
            Also Read : Import CSV file data into MongoDB using Python
        </div>
    </a>
</div>
<div class="new-line-bold">Write JSON Data to a File</div>

<div class="new-line-label">Now we can use <code>with</code> and <code>open</code> method to create a new file and write content into the file. We will convert dictionary data to json object using <code>json.dumps()</code> and write to file using <code>write()</code> method.</div>

<pre class="crayon-plain-tag">#write-program.py

import json
  
data = {
    &quot;usermame&quot; : &quot;admin&quot;,
    &quot;name&quot;: &quot;Tech Arise&quot;
    &quot;email&quot; : &quot;admin@techarise.com&quot;,
    &quot;password&quot; : &quot;admin&quot;,
}
  
userObject = json.dumps(data, indent = 4)
  
with open(&quot;user.json&quot;, &quot;w&quot;) as outFile:
    outFile.write(userObject)</pre>

<div class="new-line-bold">Read JSON File in Python</div>

<div class="new-line-label">In the above example, we read a JSON file. In this example, we will read a JSON string and parse it into a dictionary using <code>json.loads()</code></div>

<pre class="crayon-plain-tag">#read-program.py

import json

with open('user.json', 'r') as openFile:
  
    userObject = json.load(openFile)
  
print(userObject)
print(type(userObject))</pre>

<div class="new-line-bold">Output:</div>
<pre class="crayon-plain-tag">{'username': 'admin', 'name': 'Tech Arise', 'email': 'admin@techarise.com', 'password': 'admin'}
    &lt;class 'dict'&gt;</pre>
<div class="ex-read-more new-line-label">
    <a href="https://techarise.com/restful-api-in-python-mysql/" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
            Also Read : Create RESTful API using Python and MySQL
        </div>
    </a>
</div><p>The post <a href="https://techarise.com/read-write-to-json-file-in-python/">Read and Write JSON to File in Python</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></content:encoded>
					
		
		
			<dc:creator>techariseinfo@gmail.com (TechArise Team)</dc:creator></item>
		<item>
		<title>Create RESTful API using Python and MySQL</title>
		<link>https://techarise.com/restful-api-in-python-mysql/</link>
		
		
		<pubDate>Sat, 14 May 2022 17:02:24 +0000</pubDate>
				<category><![CDATA[API]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[REST API]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">https://techarise.com/?p=1398</guid>

					<description><![CDATA[<p>REST stands for Representational State Transfer. RESTful Web services are one way of providing interoperability between computer systems on the&#8230;</p>
<p>The post <a href="https://techarise.com/restful-api-in-python-mysql/">Create RESTful API using Python and MySQL</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></description>
										<content:encoded><![CDATA[<div class="new-line-label">REST stands for Representational State Transfer. RESTful Web services are one way of providing interoperability between computer systems on the Internet. Rest API help to communicate between the client app and the server application.REST is an architecture
    style for designing networked applications. A REST API defines a bunch of functions in which developers can perform requests and receive responses via HTTP protocol such as GET and POST.</div>

<div class="new-line-label">In this tutorial, you will learn how to create CRUD (create, read, update, delete) operation REST API using Python and MySQL. This is a very simple example, you can copy-paste, and change it according to your requirement.</div>

<div class="ex-read-more new-line-label">
    <a href="https://techarise.com/build-simple-rest-api-with-slim-framework/" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
            Also Read : Build Simple REST API with Slim Framework
        </div>
    </a>
</div>

<div class="top-line-bold">Before started to implement the REST API using Python and MySQL, look files structure:</div>

<ul class="tree-structure">
    <li><i class="folder-color fa fa-folder"></i> restful-api-using-python-mysql
        <ul>
            <li><i class="text-muted far fa-file"></i> app.py</li>
            <li><i class="text-muted far fa-file"></i> config.py</li>
            <li><i class="text-muted far fa-file"></i> main.py</li>
        </ul>
    </li>
</ul>


<div class="new-line-bold">Understanding REST API</div>
<div class="new-line-label">REST provides a block of HTTP methods which are used to alter the data. The following are common HTTP methods:</div>
<ul style="padding-left:30px;">
    <li><strong>GET</strong> — is used for reading and retrieving data.</li>
    <li><strong>POST</strong> — is used for inserting data.</li>
    <li><strong>PUT/PATCH</strong> — is used for updating data.</li>
    <li><strong>DELETE</strong> — is used for deleting data.</li>
</ul>

<div class="new-line-bold">Step 1: Create MySQL Database and Table </div>
<div class="new-line-label">For this tutorial, you need a MySQL database with the following table: </div>
<pre class="crayon-plain-tag">CREATE TABLE `employee` (
        `id` int(11) NOT NULL,
        `name` varchar(255) NOT NULL,
        `email` varchar(255) NOT NULL,
        `phone` varchar(16) DEFAULT NULL,
        `address` text DEFAULT NULL,
        `salary` float DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    ALTER TABLE `employee`
        ADD PRIMARY KEY (`id`);

    ALTER TABLE `employee`
        MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
        COMMIT;</pre>

<div class="new-line-bold">Step 2: Import Flask Modules</div>
<div class="new-line-label">We handle REST API functionality using <code>Flask</code> and <code>MySQL</code>, so we will need both the modules. The module Flask works as a web framework while the MySQL module requires making a connection with the MySQL database. We will create a
    project directory restful-api-using-python-mysql and move inside run cd command. We will install <code>flask</code> module by running below command. </div>
<pre class="crayon-plain-tag">pip install Flask</pre>
<div class="new-line-bold">Step 3: Run flask-cors</div>
<div class="new-line-label">Then we will install the flask-cors extension for handling Cross-Origin Resource Sharing (CORS)</div>
<pre class="crayon-plain-tag">pip install -U flask-cors</pre>

<div class="new-line-bold">Step 4: Create file </div>
<div class="new-line-label">So now we will create the app.py Python script and import the flask module and create the flask instance to use with the MySQL module. We will also import <code>flask-cors</code> extension for cross-origin (CORS).</div>

<pre class="crayon-plain-tag">from flask import Flask
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)</pre>

<div class="new-line-bold">Step 5: Create a MySQL Connection </div>
<div class="new-line-label">We will install Flask-MySQL extension using below command.</div>
<pre class="crayon-plain-tag">pip install flask-mysql</pre>
<div class="new-line-label">We will create config.py Python file to initialize MySQL database connection details to make connection with MySQL database. We will import the app script to handle MySQL database connection with Flask-MySQL module.</div>

<pre class="crayon-plain-tag">from app import app
from flaskext.mysql import MySQL

mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'restapi_DB'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)</pre>

<div class="new-line-bold">Step 6: finally create REST API CRUD Operation </div>
<div class="new-line-label">We will create a file main.py script and import the app and config modules. We will connect to the MySQL database and implement CRUD operations by defining all REST URIs.</div>

<pre class="crayon-plain-tag">import pymysql
from app import app
from config import mysql
from flask import jsonify
from flask import flash, request

@app.route('/employee/create', methods=['POST'])
def create_employee():
    try:        
        _json = request.json
        _name = _json['name']
        _email = _json['email']
        _phone = _json['phone']
        _address = _json['address']	
        _salary = _json['salary']	

        if _name and _email and _phone and _address and _salary and request.method == 'POST':
            conn = mysql.connect()
            cursor = conn.cursor(pymysql.cursors.DictCursor)		
            sqlQuery = &quot;INSERT INTO employee(name, email, phone, address, salary) VALUES(%s, %s, %s, %s, %s)&quot;
            bindData = (_name, _email, _phone, _address, _salary)            
            cursor.execute(sqlQuery, bindData)
            conn.commit()
            cursor.close() 
            respone = jsonify('Employee created successfully!')
            respone.status_code = 200
            return respone
        else:
            return showMessage()
    except Exception as err:
        print(err)
    finally:
        
        conn.close()          
    
@app.route('/employee')
def employee():
    try:
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute(&quot;SELECT id, name, email, phone, address, salary FROM employee&quot;)
        empRows = cursor.fetchall()
        respone = jsonify(empRows)
        respone.status_code = 200
        return respone
    except Exception as err:
        print(err)
    finally:
        cursor.close() 
        conn.close()  

@app.route('/employee/&lt;int:employee_id&gt;')
def employee_details(employee_id):
    try:
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute(&quot;SELECT id, name, email, phone, address, salary FROM employee WHERE id =%s&quot;, employee_id)
        empRow = cursor.fetchone()
        respone = jsonify(empRow)
        respone.status_code = 200
        return respone
    except Exception as err:
        print(err)
    finally:
        cursor.close() 
        conn.close() 

@app.route('/employee/update', methods=['PUT'])
def update_employee():
    try:
        _json = request.json
        _id = _json['id']
        _name = _json['name']
        _email = _json['email']
        _phone = _json['phone']
        _address = _json['address']
        _salary = _json['salary']
        if _name and _email and _phone and _address and _id and request.method == 'PUT':			
            sqlQuery = &quot;UPDATE employee SET name=%s, email=%s, phone=%s, address=%s, salary=%s WHERE id=%s&quot;
            bindData = (_name, _email, _phone, _address, _salary, _id,)
            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.execute(sqlQuery, bindData)
            conn.commit()
            respone = jsonify('Employee updated successfully!')
            respone.status_code = 200
            return respone
        else:
            return showMessage()
    except Exception as err:
        print(err)
    finally:
        cursor.close() 
        conn.close() 

@app.route('/employee/delete/&lt;int:employee_id&gt;', methods=['DELETE'])
def delete_employee(employee_id):
    try:
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute(&quot;DELETE FROM employee WHERE id =%s&quot;, (employee_id,))
        conn.commit()
        respone = jsonify('Employee deleted successfully!')
        respone.status_code = 200
        return respone
    except Exception as err:
        print(err)
    finally:
        cursor.close() 
        conn.close()
        
@app.errorhandler(404)
def showMessage(error=None):
    message = {
        'status': 404,
        'message': 'Record not found: ' + request.url,
    }
    respone = jsonify(message)
    respone.status_code = 404
    return respone
        
if __name__ == &quot;__main__&quot;:
    app.run()</pre>

<div class="new-line-bold">Step 7: Run Application </div>
<div class="new-line-label">Now we will go the project <code>restful-api-using-python-mysql</code> and run command <code>python main.py</code> and the server will start on default PORT 5000. We will use Postman to run Python RESTful API with (POST, GET, PUT or DELETE) methods to
    run it.</div>

<div class="new-line-label">We will run the below URL and create new employee record with the POST HTTP method.</div>
<pre class="crayon-plain-tag">http://127.0.0.1:5000/employee/create</pre>
<div class="new-line-label">The request body will be following:</div>

<img data-recalc-dims="1" fetchpriority="high" decoding="async" src="https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/created-emp-1024x383.png?resize=769%2C288&#038;ssl=1" alt="" width="769" height="288" class="alignnone size-large wp-image-1399" srcset="https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/created-emp.png?resize=1024%2C383&amp;ssl=1 1024w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/created-emp.png?resize=300%2C112&amp;ssl=1 300w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/created-emp.png?resize=768%2C287&amp;ssl=1 768w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/created-emp.png?resize=769%2C288&amp;ssl=1 769w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/created-emp.png?w=1380&amp;ssl=1 1380w" sizes="(max-width: 769px) 100vw, 769px" />

<div class="new-line-label">We will run the below URL with HTTP GET method to get all employee data returned in JSON format.</div>
<pre class="crayon-plain-tag">http://127.0.0.1:5000/employee</pre>
<div class="new-line-label">The request body will be following:</div>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/list-emp-1024x530.png?resize=769%2C398&#038;ssl=1" alt="" width="769" height="398" class="alignnone size-large wp-image-1400" srcset="https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/list-emp.png?resize=1024%2C530&amp;ssl=1 1024w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/list-emp.png?resize=300%2C155&amp;ssl=1 300w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/list-emp.png?resize=768%2C397&amp;ssl=1 768w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/list-emp.png?resize=769%2C398&amp;ssl=1 769w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/list-emp.png?w=1372&amp;ssl=1 1372w" sizes="(max-width: 769px) 100vw, 769px" />

<div class="new-line-label">We will get the employee data using the below URL with HTTP  GET method.</div>
<pre class="crayon-plain-tag">http://127.0.0.1:5000/employee/1</pre>
<div class="new-line-label">The request body will be following:</div>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/emp-details.png?resize=769%2C358&#038;ssl=1" alt="" width="769" height="358" class="alignnone size-large wp-image-1401" srcset="https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/emp-details.png?resize=1024%2C477&amp;ssl=1 1024w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/emp-details.png?resize=300%2C140&amp;ssl=1 300w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/emp-details.png?resize=768%2C358&amp;ssl=1 768w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/emp-details.png?resize=769%2C359&amp;ssl=1 769w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/emp-details.png?w=1377&amp;ssl=1 1377w" sizes="(max-width: 769px) 100vw, 769px" />

<div class="new-line-label">We will update existing employee data using HTTP PUT method.</div>
<pre class="crayon-plain-tag">http://127.0.0.1:5000/employee/update</pre>
<div class="new-line-label">The request body will be following:</div>

<img data-recalc-dims="1" loading="lazy" decoding="async" src="https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/update-emp-1024x480.png?resize=769%2C360&#038;ssl=1" alt="" width="769" height="360" class="alignnone size-large wp-image-1402" srcset="https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/update-emp.png?resize=1024%2C480&amp;ssl=1 1024w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/update-emp.png?resize=300%2C141&amp;ssl=1 300w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/update-emp.png?resize=768%2C360&amp;ssl=1 768w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/update-emp.png?resize=769%2C360&amp;ssl=1 769w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/update-emp.png?w=1372&amp;ssl=1 1372w" sizes="auto, (max-width: 769px) 100vw, 769px" />

<div class="new-line-label">We will delete existing employee data using HTTP DELETE method.</div>
<pre class="crayon-plain-tag">http://127.0.0.1:5000/employee/delete/1</pre>
<div class="new-line-label">The request body will be following:</div>

<img data-recalc-dims="1" loading="lazy" decoding="async" src="https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/delete-emp-1024x463.png?resize=769%2C348&#038;ssl=1" alt="" width="769" height="348" class="alignnone size-large wp-image-1403" srcset="https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/delete-emp.png?resize=1024%2C463&amp;ssl=1 1024w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/delete-emp.png?resize=300%2C136&amp;ssl=1 300w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/delete-emp.png?resize=768%2C347&amp;ssl=1 768w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/delete-emp.png?resize=769%2C347&amp;ssl=1 769w, https://i0.wp.com/techarise.com/wp-content/uploads/2022/05/delete-emp.png?w=1377&amp;ssl=1 1377w" sizes="auto, (max-width: 769px) 100vw, 769px" />

<div class="ex-read-more new-line-label">
    <a href="https://techarise.com/nodejs-restfull-apis-with-express-and-mysql/" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
            Also Read : NodeJS RESTfull APIs with Express and MySQL
        </div>
    </a>
</div>

<div class="new-line-label">
    <a class="btn btn-primary" title="Download" href="https://techarise.com/source-code/download/rest-api-slim-0A9DF635-894Z-4590-0346" target="_balnk" rel="noopener noreferrer"><i class="fa fa-fw fa-download text-right"></i> Download</a>
</div><p>The post <a href="https://techarise.com/restful-api-in-python-mysql/">Create RESTful API using Python and MySQL</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></content:encoded>
					
		
		
			<dc:creator>techariseinfo@gmail.com (TechArise Team)</dc:creator></item>
		<item>
		<title>Import CSV file data into MongoDB using Python</title>
		<link>https://techarise.com/import-csv-file-into-mongodb-using-python/</link>
		
		
		<pubDate>Thu, 14 Apr 2022 14:09:43 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">https://techarise.com/?p=1387</guid>

					<description><![CDATA[<p>In this tutorial, we will share with you how to import CSV file data into MongoDB using Python. While developing&#8230;</p>
<p>The post <a href="https://techarise.com/import-csv-file-into-mongodb-using-python/">Import CSV file data into MongoDB using Python</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></description>
										<content:encoded><![CDATA[<div class="new-line-label">In this tutorial, we will share with you how to import CSV file data into MongoDB using Python. While developing an application using Python, sometimes we need to insert CSV data into the MongoDB database. Inserting CSV data to MongoDB is very easy in Python. We just need t read the CSV file and then connect to MongoDB to insert data. We will use CSV built-in module to read CSV files. We will use module <code>pymongo</code> to connect with the <code>MongoDB</code> client and insert data.</div>

<div class="ex-read-more">
    <a href="https://techarise.com/codeigniter-import-export-csv-file-data-into-mysql" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
           Also Read : Import/Export Data to CSV file with CodeIgniter and MySQL
        </div>
    </a>
</div>

<div class="new-line-bold">So let’s start firstly Install PyMongo Module :</div>

<div class="new-line-bold">Install PyMongo Module</div>
<div class="new-line-label">
As we need to connect with the MongoDB client, so we need to install <code>pymongo</code> module using below command.</div>

<pre class="crayon-plain-tag">pip install pymongo</pre>

<div class="new-line-bold">Connect to MongoDB</div>
<div class="new-line-label">We will import module <code>pymongo</code> to connect with MongoDB to insert records.</div>
<pre class="crayon-plain-tag">from pymongo import MongoClient</pre>
<div class="new-line-label">We will configure MongoDB connection details and connection to the database and collection to insert records.</div>

<pre class="crayon-plain-tag">mongoClient = MongoClient() 
db = mongoClient.october_mug_talk
db.segment.drop()</pre>

<div class="new-line-bold">Reading CSV File</div>

<div class="new-line-label">As we will insert CSV file data to the MongoDB. So we will import the CSV module at the top of the file to read the CSV file.</div>
<pre class="crayon-plain-tag">import csv</pre>
<div class="new-line-label">We will CSV file employee using <code>DictReader()</code> method. The <code>DictReader()</code> function returns a csv reader object.</div>

<pre class="crayon-plain-tag">csvfile = open('current.csv', 'r')
reader = csv.DictReader( csvfile )</pre>
<div class="new-line-label">We will iterate over CSV reader object and create JSON data to insert multiple records into MongoDB.</div>

<pre class="crayon-plain-tag">for each in reader:
    row={}
    for field in header:
        row[field]=each[field]</pre>

<div class="new-line-bold">Insert data into MongoDB</div>

<div class="new-line-label">We will insert json row data into MongoDB.</div>

<pre class="crayon-plain-tag">db.segment.insert(row)</pre>

<div class="new-line-bold">Final code to insert CSV data into MongoDB</div>
<div class="new-line-label">Now you can insert the JSON in your MongoDB database.</div>

<pre class="crayon-plain-tag">import csv
import json
import pandas as pd
import sys, getopt, pprint
from pymongo import MongoClient
#Conversion CSV to JSON 
csvfile = open('current.csv', 'r')
reader = csv.DictReader( csvfile )
mongo_client=MongoClient() 
db=mongo_client.october_mug_talk
db.segment.drop()
header= [ &quot;First Name&quot;, &quot;Last Name&quot;, &quot;Email&quot;, &quot;Mobile&quot;, &quot;Address&quot;, &quot;Date&quot;]

for each in reader:
    row={}
    for field in header:
        row[field]=each[field]

    db.segment.insert(row)</pre>

<div class="ex-read-more">
    <a href="https://techarise.com/import-excel-file-mysql-codeigniter" target="_blank" class="ex-also-read-more" rel="noopener noreferrer">
        <div class="ex-link-read-more">
           Also Read : Import/Upload Excel file into MySQL using Codeigniter
        </div>
    </a>
</div><p>The post <a href="https://techarise.com/import-csv-file-into-mongodb-using-python/">Import CSV file data into MongoDB using Python</a> first appeared on <a href="https://techarise.com">Tech Arise</a>.</p>]]></content:encoded>
					
		
		
			<dc:creator>techariseinfo@gmail.com (TechArise Team)</dc:creator></item>
	</channel>
</rss>