Categories
PHP Programming

Installing PHP on Windows

What is PHP?

PHP is known to be one of the most commonly used server-side programming language on the web. It provides an easy to master with a simple learning curve. It has close ties with the MySQL database, and various libraries to cut your development time.

Two Ways to install PHP locally

There are several ways that we could install PHP locally. Here i have added two of the most common ways to install PHP as shown below.

  1. Installing a Web Server (XAMPP, WAMP etc)
  2. Implementing via PHP Installer
Installing a Web Server

There are many all-in-one packages are available for Windows and other OSโ€™s which comes with Apache, PHP, MySQL and other applications as a single file installer, e.g. XAMPP, WampServer, MAMP etc. There is no any issue in going with these packages, however manually installing Apache and PHP will help you to have more control and access to its configuration options.

XAMPP :
https://www.apachefriends.org/index.html

WampServer :
https://www.wampserver.com/en/

MAMP :
https://www.mamp.info/en/windows/

Implementing via PHP Installer

It provides several benefits for backing up, reinstalling, or moving the web server can be executed easily in a short amount of time and it provides more control over PHP and Apache configuration. In the Manual Installation, you need to configure several steps in order to install PHP successfully.

Step 1 : Download the PHP package & Extract THE FILES

Get the PHP version 8.0 or later (x64 Thread Safe) package zip file via navigating under the windows downloads URL mentioned in the link below.

https://www.php.net/downloads.php.

After, downloading the zip successfully to your PC, create a folder as “PHP” in any drive and extract the PHP package files into it.

STEP 2 : CONFIGURE PHP

Initially php.ini file doesn’t exist inside the php package files. so copy {drive_name}:\php\php.ini-development and rename it as {drive_name}:\php\php.ini whereas the default configuration provides a development setup.

To uncomment a setting inside the php.ini file you need to remove a leading semicolon (;). Uncomment the following lines to enable the required extensions whereas the following extensions are mostly required by many PHP frameworks and for other operations.

extension=curl extension=gd extension=mbstring extension=pdo_mysql
Step 3 : Add PHP to The environment variable

To access PHP globally at your PC add the PHP package path by following the steps below.

  • Step 1: Click the Windows Start button and type โ€œenvironmentโ€.
  • Step 2: Click Edit the system environment variables. Select the Advanced tab, and click the Environment Variables button.
  • Step 3: Scroll down the System variables list and click Path followed by the Edit button.
  • Step 4 : Click New and add {drive_name}:\php:

NOTE: You are not required to reboot the PC, but you may need to close and restart any cmd terminals if you have opened before.

STEP 4 : Test a PHP file

Create a new file named index.php and add the following lines of codes and save it.

<?php phpinfo(); ?>
Code language: HTML, XML (xml)

Run the PHP file by entering the following command in CMD where you have created the index.php file.

php index.php
Code language: CSS (css)
Categories
Programming

Top 5 Programming languages to learn in 2020

Programming is one of the most important skill to be mastered in todayโ€™s world. If you are new to the field of software engineering, the very first question comes to your mind is โ€œWhatโ€™s the best Programming Language to Master ?โ€ thatโ€™s an important question to decide your programming career. There are many popular programming languages to learn in 2020. Letโ€™s find out the best 5 programming languages to master.

Disclaimer :

The information provided in this article is my own personal opinion and it’s no mean of degrading any programming languages available today. Feel free to share your opinion in the comment section.

#1 Python

Python

Python is a high-level, general-purpose programming language which has been emerging in 2020 as one of the most frequently used language in the area of data science, Artificial Intelligence and Machine Learning. Created by Guido van Rossum. Python has been a growing programming language ever since the release. Python is largely used in web applications, desktop apps, network servers, machine learning and more. Python is considered to be the fastest language and it’s very easy to learn and it has fewer syntactical constructions than other languages.

Learn Python via Learn to CODE

Data scientists and people from Computer Science have involved in scripting based open-source language. to use it for their ML algorithms, techniques, and Jobs in Data Science.

Python is comparatively easy to learn and code with minimal syntax. It provides a huge array of in-built libraries and frameworks for Data Science which consist of Bokeh, Pandas, Numpy, Scipy, Matplotlib, StatsModel with extension framework for Deep learning include

  • Theano.
  • Lasagne.
  • Blocks.
  • TensorFlow.
  • Keras.
  • MXNet.
  • PyTorch.

Here is an example for a simple Python โ€œHello World!โ€ program:

print ("Hello World!")
Code language: PHP (php)
Learning CurveEasy to Learn
Job opportunityHigher

#2 JS

JS

JavaScript is used as the โ€œfrontendโ€ programming language in web apps. It’s most commonly used as a client-side scripting language. If you have mastered any other programming languages before, then learning JavaScript will be much easier for you.

Why JavaScript is Used?

JavaScript is commonly known for its usability for the front-end of the web. Although JS is used for many other areas. Along with the front-end of the web, It’s been widely used for the following areas.

JS powered Mobile Applications

Most of the Mobile Applications are developed using Native Languages which are provided by their OS (Operating System). Although Cross-Platform Development is widely used to get rid of the pain of coding more than once. The mobile JS frameworks like React Native and PhoneGap are created to facilitate Android and iOS development with one single code base. This helps the developers to use JS to build mobile applications easily.

Web Applications

JS is not only limited to front-end development for the interactive web. But the development of new frameworks and libraries are allowing users to develop a lot of back-end programs with JS. which includes interactive web apps and server apps. JS is widely used in previous years and it continues to grow because of its flexibility and speed. These are few of the JavaScript frameworks popularly used by developers today.

Games

Most of the developers are very familiar with JS than other languages. Due to this, It’s possible to develop games via JS. When it comes to the modern browsers They have the capability of rendering WebGL, they can render complex 3D and 2D graphics without the need for third-party applications. These are some of the JS engines to build games.

Here is an example of a simple JavaScript โ€œHello World!โ€ program:

<script> document.getElementById("demo").innerHTML = "Hello JavaScript!"; </script>
Code language: HTML, XML (xml)
Learning CurveIf you are fluent in any other languages. then it’s easy to learn.
Job opportunityHigh

#3 Java

Java is a general-purpose, high-level programming language. It’s intended to let application developers โ€œwrite once, run anywhereโ€ (WORA), meaning that compiled Java code can run on all platforms. Java was originally developed by James Gosling at Sun Microsystems (which has since been acquired by Oracle Corporation) and released in 1995.

Java is also widely used in Mobile Application Development, Web Application Development and Creating Desktop Applications.

  1. Desktop Base Applications :Desktop Applications can be created using libraries like Java Swing or JavaFX. They provide components to create text boxes, graphics and buttons for the GUI.
  2. Web Base Applications : Java provides support for web application through Servlets and JSPs.
  3. Mobile Base Applications : Native Android Applications are written in Java. Furthermore, Android Studio provides development tools for developing in Java.

Here is an example of a simple Java โ€œHello World!โ€ program:

class Hello { public static void main(String args[]){ System.out.println("Hello World"); } }
Code language: JavaScript (javascript)
Learning CurveIf you are good at OOP. then, It would be easy to learn.
Job opportunityHigher

#4 Kotlin

Kotlin

Kotlin is founded by JetBrains and it has been open source since 2012. It’s an Open Source, General Purpose statically typed pragmatic programming language for the Android and Java Virtual Machine. You can find the Open Source Kotlin Project on GitHub. Kotlin is becoming one of the trending languages in 2020.

Google Announced the support for Kotlin in Android Studio IDE three years back at I/O 2017. Which led the long-time preferred language Java for Android to switch into Kotlin.

The Syntax of Kotlin is minimal, clean and modern. It’s very easy to learn Kotlin because of it’s minimal and easy to understand nature. It’s similar to Apple’s Swift Language.

Here is an example of a simple Kotlin โ€œHello World!โ€ program:

println("Hello World!")
Code language: JavaScript (javascript)

The support of Kotlin Multiplatform aims to extend the compatibility to other platforms and it incorporates the developers to reuse the code and their expertise by reducing the tasks to implement twice or thrice.

With the swift growth of its presence among the developers, Kotlin is already in a phase of adapting to Data Science. Some of the following tools and libraries are now supporting data science as listed below.

  • Apache Spark & Apache Zeppelin: Kotlin is used in Spark Java API from both Jupyter and Zeppelin.
  • Jupyter: Now you can use Kotlin kernel for Jupyter notebooks by accessing third-party data science frameworks written in Java and Kotlin.

Learn the basics of Kotlin with Learn to CODE

Learning CurveRelatively easy to learn when comparing to other languages. The syntax is similar to JAVA.
Job opportunityHigh

#5 Swift

Swift is a high-level, Open Source, General-Purpose, Compiled programming language created for iOS Development, OS X, watchOS by Apple. Swift language is based on Objective-C, which was used for NeXTSTEP development. It’s an alternative to the Objective-C language which was the most popular language for building apps for Apple Platform.

Swift is easy to use and with syntactic simplicity to match Python. Which can be used to build apps much faster with less learning curve.

Here is an example of a simple Swift โ€œHello World!โ€ program:

import Swift print("Hello, World!")
Code language: JavaScript (javascript)
Learning CurveSoft Learning Curve.
Job opportunityHigh

That ends the list of top five programming languages in 2020. If you like the article please share with others and drop your ideas and suggestions in the comment section.

Categories
PHP

PHP Array Functions and their usage with examples

This tutorial is created to give an abstract idea about commonly used PHP array function with examples. Through this tutorial you’ll be able to know, how to use array functions to make code more short and simple.

Note:

I’ll be only covering some of the basicย array functions, Which were frequently used by PHP developers. You can refer all the array functions from the officialย PHP Documentation. Feel free to share your opinion in the comment section.

Creating an Array in PHP

PHP array is created using an array() function. There are basically three types of arrays in PHP

  1. Indexed arrays – An array with a numeric index.
  2. Associative arrays – An array with named keys.
  3. Multidimensional arrays – An array containing one or more arrays.

To create an indexed array, add array values inside the parentheses, separated by commas.

$randomNames = array("Peace","Love","BH","Bishrul","Haq");
Code language: PHP (php)

OR

$randomNames = array(); $randomNames[0] = "Peace"; $randomNames[1] = "Love"; $randomNames[2] = "BH"; $randomNames[3] = "Bishrul"; $randomNames[4] = "Haq";
Code language: PHP (php)

Let’s look into some of the PHP functions in detail.

  1. List()

List function is used to Assign variables as if they were an array. It helps to insert without assigning values to each array index.

$names = array("Dev","BH","Peace"); // without list function() $one = $names[0]; $two = $names[1]; $three = $names[2]; // with list function() list($one,$two,$three) = $names; echo 'one : '. $one.' two : '. $two.' three : '. $three;
Code language: PHP (php)

Output

Array ( [0] => BH [1] => is [2] => Carm )
Code language: PHP (php)
  1. preg_slit() or explode()

These two functions are used to split a string by a given string. Which helps to skip string, if you don’t need them to be shown.

$words = 'BH|is|Carm'; $array = explode('|', $words); // exploded words are displayed in the array print_r($array);
Code language: PHP (php)

Output

one : Dev two : BH three : Peace
  1. extract()

extract() function is used to export an associative array to variables. For every array element, a variable will be created with the name of a key and value as a value of the element.

$details = [ 'name' => 'bishrul', 'age' => '24', 'color' => 'fair', ]; extract($details); echo("$name $age $color");
Code language: PHP (php)

Output

bishrul 24 fair
  1. compact()

It’s the exact opposite of explode() function, Which convert the given variables into an associative array.

$name = 'bishrul'; $age = '24'; $color = 'fair'; $array = compact('name', 'age', 'color'); print_r($array);
Code language: PHP (php)

Output

Array ( [name] => bishrul [age] => 24 [color] => fair )
Code language: PHP (php)
  1. array_combine()

Which creates an array by using one array for array keys and another for its array values.

$keys = ['name', 'age', 'color']; $values = ['bishrul', '24', 'fair']; $details = array_combine($keys, $values); print_r($details);
Code language: PHP (php)

Output

Array ( [name] => bishrul [age] => 24 [color] => fair )
Code language: PHP (php)
  1. array_merge()

To merge two or more arrays into one array array_merge() is used. values of arrays will be merged together, and values with the same keys will be overwritten with the last array.

$array1 = ['one' => '1', 'two' => '2', 'three' => '3']; $array2 = ['one' => '11', 'four' => '4', 'three' => '33']; $merge = array_merge($array1, $array2); print_r($merge);
Code language: PHP (php)

Output

Array ( [one] => 11 [two] => 2 [three] => 33 [four] => 4 )
Code language: PHP (php)
  1. array_sum() & array_product()

array_sum() is used to get the sum of given array values and array_product() to multiply the given array values.

$values = [4, 4, 3, 1, 5]; echo('Sum :'.array_sum($values).' Product :'. array_product($values));
Code language: PHP (php)

Output

Sum :17 Product :240
Code language: CSS (css)

If you like the article please share with others and drop your ideas and suggestions at the comment section.

Categories
PHP

PHP Program to remove empty or specific array elements.

This tutorial is created to remove specific or empty (NULL) array elements from the array.

  1. array_filter() to Remove Empty Elements

array_filter() function removes false values when declared using a callback function, however, If the callback function returns true, the current value from input is returned into the result array.

  1. $array (mandatory): This is where the input array is given.
  2. $callback_function (optional): The user-defined function is given . If the function is not given then all entries of the array equal to FALSE and will be removed.
  3. $flag (optional): The arguments passed to the callback function is defined.
    • ARRAY_FILTER_USE_KEY โ€“ Only key argument is passed to the callback function, instead of the value of the array.
    • ARRAY_FILTER_USE_BOTH โ€“ Both value and key as arguments to callback instead of the value.

Syntax :

array array_filter($array, $callback_function, $flag)
Code language: PHP (php)

Below is a program showing how to return filtered array elements using array_filter() function.

<?php // Declaring the array $array = array("bishrul", 27, '', null, "developer", 45,"for", 1994, false,); // Function to remove empty elements $filtered_array = array_filter($array); // Display the array var_dump($filtered_array);
Code language: HTML, XML (xml)

Output :

array(6) { [0]=> string(7) "bishrul" [1]=> int(27) [4]=> string(9) "developer" [5]=> int(45) [6]=> string(3) "for" [7]=> int(1994) }
Code language: PHP (php)
  1. unset() Function to Remove Empty Elements.

The Another way is to remove empty elements from array is using empty() function along with the unset() function. The empty() function is used to check whether the element is empty is not.

<?php // Declaring the array $array = array("bishrul", 27, '', null, "developer", 45,"for", 1994, false,); // Loop to find empty elements foreach($array as $key => $value) if(empty($value)){ unset($array[$key]); } // Displaying the array foreach($array as $key => $value) echo ($array[$key] . " , "); ?>
Code language: HTML, XML (xml)

Output :

bishrul , 27 , developer , 45 , for , 1994 ,

Removing a specific value using unset() function in PHP.

<?php // Declaring the array $array = array("bishrul", 27, '', null, "developer", 45,"for", 1994, false,); // Loop to find empty elements foreach($array as $key => $value) if($value == "bishrul"){ unset($array[$key]); } // Displaying the array foreach($array as $key => $value) echo ($array[$key] . " , "); ?>
Code language: HTML, XML (xml)

Output :

27 , , , developer , 45 , for , 1994 , ,

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Categories
PHP

Simple PHP MySQL CRUD Application

PHP is widely used by many developers today and it’s one of the easiest language to learn. This tutorial will help you to learn the basic CRUD (Create, Read, Update, Delete) operations in PHP using MYSQL.

PHP CRUD
  1. Create the DB(Database) file

Create the DB as ‘php_crud’ and run the following SQL query to create table users inside the MySQL ‘php_crud’ database.

Creating the DB
Creating the DB

SQL query to create a table named users

Table in PHP CRUD
Creating the Table
CREATE TABLE users ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100) NOT NULL, address VARCHAR(255) NOT NULL, age INT(10) NOT NULL );
Code language: PHP (php)

Now, It’s time to create the DB config.php file as shown below

config.php

<?php define('DB_SERVER', 'localhost'); define('DB_USERNAME', ''); define('DB_PASSWORD', ''); define('DB_NAME', 'php_crud'); $link = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME); if ($link->connect_errno) { printf("Connect failed: %s\n", $link->connect_error); exit(); }
Code language: HTML, XML (xml)
  1. Creating the Pages

Create the landing page for the CRUD application that contains a table to show the records from the users table.

index.php

<?php require_once "config.php"; $sql = "SELECT * FROM users"; $result = $link->query($sql); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>PHP CRUD : bishrulhaq.com</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> .btn{ margin-left: 10px; } </style> </head> <body> <div class="wrapper"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="card" style="margin-top: 20px;margin-bottom: 20px;"> <div class="card-body"> <h2 class="pull-left">User Details <a href="create.php" class="btn btn-success pull-right">Add New User</a></h2> <h6>Find more interesting tutorials at <a href="https://bishrulhaq.com/">bishrulhaq.com</a></h6> </div> </div> <?php if ($result->num_rows > 0) { echo "<table class='table table-bordered table-striped'>"; echo "<thead>"; echo "<tr>"; echo "<th>#</th>"; echo "<th>Name</th>"; echo "<th>Address</th>"; echo "<th>Age</th>"; echo "<th>Action</th>"; echo "</tr>"; echo "</thead>"; echo "<tbody>"; while ($row = $result->fetch_assoc()) { echo "<tr>"; echo "<td>" . $row['id'] . "</td>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['address'] . "</td>"; echo "<td>" . $row['age'] . "</td>"; echo "<td>"; echo "<a href='read.php?id=" . $row['id'] . "' class='btn btn-primary'>Read</a>"; echo "<a href='update.php?id=" . $row['id'] . "' class='btn btn-info'>Update</a>"; echo "<a href='delete.php?id=" . $row['id'] . "' class='btn btn-danger'>Delete</a>"; echo "</td>"; echo "</tr>"; } echo "</tbody>"; echo "</table>"; // Free result set $result->free(); } else { echo "<p class='lead'><em>No records were found.</em></p>"; } $link->close(); ?> </div> </div> </div> </div> </body> </html>
Code language: HTML, XML (xml)

In this step, Let’s create the “create.php” and add the following code inside it.

create.php

<?php require_once "config.php"; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_POST['name']) && isset($_POST['address']) && isset($_POST['age'])) { $sql = "INSERT INTO users (name, address, age) VALUES (?,?,?)"; if ($stmt = $link->prepare($sql)) { $stmt->bind_param("ssi", $_POST['name'], $_POST['address'], $_POST['age']); if ($stmt->execute()) { header("location: index.php"); exit(); } else { echo "Error! Please try again later."; } $stmt->close(); } } $link->close(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Create User : bishrulhaq.com</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <div class="wrapper"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="page-header"> <h2>Create Users</h2> </div> <p>Fill this form to add users to the database.</p> <form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post"> <div class="form-group"> <label>Name</label> <input type="text" name="name" class="form-control" required> </div> <div class="form-group"> <label>Address</label> <textarea name="address" class="form-control" required></textarea> </div> <div class="form-group"> <label>Age</label> <input type="number" name="age" class="form-control" required> </div> <input type="submit" class="btn btn-primary" value="Submit"> <a href="index.php" class="btn btn-default">Cancel</a> </form> </div> </div> </div> </div> </body> </html>
Code language: HTML, XML (xml)

Create “delete.php” and add the following code inside it. Which will help to delete a particular user by passing the ID.

delete.php

<?php if (isset($_GET["id"]) && !empty($_GET["id"])) { require_once "config.php"; $sql = "DELETE FROM users WHERE id = ?"; if ($stmt = $link->prepare($sql)) { $stmt->bind_param("i", $_GET["id"]); if ($stmt->execute()) { header("location: index.php"); exit(); } else { echo "Error! Please try again later."; } } $stmt->close(); $link->close(); } else { echo "Error! Please try again later."; } ?>
Code language: HTML, XML (xml)

Now, Let’s Create the “read.php” and add the following code inside it.

read.php

<?php require_once "config.php"; if (isset($_GET["id"]) && !empty(trim($_GET["id"]))) { $sql = "SELECT * FROM users WHERE id = ?"; if ($stmt = $link->prepare($sql)) { $stmt->bind_param("i", $_GET["id"]); if ($stmt->execute()) { $result = $stmt->get_result(); if ($result->num_rows == 1) { $row = $result->fetch_array(MYSQLI_ASSOC); $name = $row["name"]; $address = $row["address"]; $age = $row["age"]; } else { echo "Error! Please try again later."; exit(); } } else { echo "Error! Please try again later."; exit(); } } $stmt->close(); $link->close(); } else { echo "Error! Please try again later."; exit(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>View User : bishrulhaq.com</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> label{ font-weight: bold; } </style> </head> <body> <div class="wrapper"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="card" style="margin-top: 20px;"> <div class="card-body"> <div class="page-header"> <h1>View User</h1> </div> <div class="form-group"> <label >Name</label> <p class="form-control-static"><?php echo $name; ?></p> </div> <div class="form-group"> <label>Address</label> <p class="form-control-static"><?php echo $address; ?></p> </div> <div class="form-group"> <label>Age</label> <p class="form-control-static"><?php echo $age; ?></p> </div> <p><a href="index.php" class="btn btn-primary">Back</a></p> </div> </div> </div> </div> </div> </div> </body> </html>
Code language: HTML, XML (xml)

Create “update.php” and add the following code inside it. Which will help to update the particular user data

update.php

<?php require_once "config.php"; if (isset($_GET['id'])) { $sql = "SELECT * FROM users WHERE id = ?"; if ($stmt = $link->prepare($sql)) { $stmt->bind_param("i", $_GET["id"]); if ($stmt->execute()) { $result = $stmt->get_result(); if ($result->num_rows == 1) { $row = $result->fetch_array(MYSQLI_ASSOC); $param_name = $row["name"]; $param_address = $row["address"]; $param_age = $row["age"]; } else { echo "Error! Data Not Found"; exit(); } } else { echo "Error! Please try again later."; exit(); } $stmt->close(); } } else { header("location: index.php"); exit(); } if ($_SERVER["REQUEST_METHOD"] == "POST") { if (!empty($_POST["name"]) && !empty($_POST["address"]) && !empty($_POST["age"])) { $sql = "UPDATE users SET name = ?, address = ?, age = ? WHERE id = ?"; if ($stmt = $link->prepare($sql)) { $stmt->bind_param("ssii", $_POST["name"], $_POST["address"], $_POST["age"], $_GET["id"]); $stmt->execute(); if ($stmt->error) { echo "Error!" . $stmt->error; exit(); } else { header("location: index.php"); exit(); } $stmt->close(); } } $link->close(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Update User : bishrulhaq.com</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> label{ font-weight: bold; } </style> </head> <body> <div class="wrapper"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="card" style="margin-top:20px;"> <div class="card-body"> <div class="page-header"> <h2>Update User</h2> </div> <p>Edit the input to update the User.</p> <form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post"> <div class="form-group"> <label>Name</label> <input type="text" name="name" class="form-control" required value="<?php echo $param_name; ?>"> </div> <div class="form-group"> <label>Address</label> <textarea name="address" class="form-control" required ><?php echo $param_address; ?></textarea> </div> <div class="form-group"> <label>Age</label> <input type="text" name="age" class="form-control" value="<?php echo $param_age; ?>" required> </div> <input type="submit" class="btn btn-primary" value="Submit"> <a href="index.php" class="btn btn-default">Cancel</a> </form> </div> </div> </div> </div> </div> </div> </body> </html>
Code language: HTML, XML (xml)

Hope this tutorial helped you! Feel free to drop your opinion in the comment section.

Categories
Laravel

CRUD in Laravel 5.8

This tutorial is created to illustrate the basic CRUD (Create , Read, Update, Delete) operation using SQL with Laravel 5.8. Laravel is one of the fastest growing frameworks for PHP built by Taylor Otwell.

# Laravel 5.8

Laravel 5.8 continues the improvements made in the previous release (version 5.7). Referย release notesย to see the changes made in Laravel 5.8.

In this tutorial, You’ll learn the Basic CRUD operation in Laravel. Follow the step by step guide to create the CRUD application.

  1. Install Laravel

First, let install Laravel using the following command (Make sure you have installed composer in your PC). Click on Install Composer If you haven’t installed Composer on your PC.

composer create-project --prefer-dist laravel/laravel students
Code language: PHP (php)
  1. Configure Database Details

You need to create the database at MYSQL and then we need to connect that database to the Laravel project (You can also use phpmyadmin to create the database). Open the .env file inside Laravel project and add the database credentials as below.

.env

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE='Your DB Name' DB_USERNAME='Your DB UserName' DB_PASSWORD='Your DB Password'
Code language: PHP (php)
  1. Create the migration file.

Go to the terminal and type the following php artisan command to generate the model and migration file.

php artisan make:migration create_students_table --create=students
Code language: PHP (php)

The migration will be created under “database/migrations“. Edit the file with the code below to create Students Table.

create_students_table.php

<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateStudentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('students', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->text('detail'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('students'); } }
Code language: Ceylon (ceylon)

Type the following command to run the migration.

php artisan migrate
  1. Create route, controller and model

In this step, Go to ‘routes->web.php’ file, add the following line of code.

//redirect to the students resource controller Route::get('/', function () { return redirect('/students'); }); Route::resource('students','StudentController');
Code language: PHP (php)

Create the Student model using the following command.

php artisan make:model Student
Code language: PHP (php)

The model wil be generated in “app/Student.php” Now, we will write the schema inside Student.php file.

Student.php

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model { protected $fillable = [ 'name', 'detail' ]; }
Code language: PHP (php)

Create the StudentController as resource using the following command.

php artisan make:controller StudentController --resource --model=Student
Code language: PHP (php)

app/Http/Controllers/StudentController.php

<?php namespace App\Http\Controllers; use App\Student; use Illuminate\Http\Request; class StudentController extends Controller { public function index() { $students = Student::latest()->paginate(5); return view('students.index',compact('students'))->with('i', (request()->input('page', 1) - 1) * 5); } public function create() { return view('students.create'); } public function store(Request $request) { $request->validate([ 'name' => 'required', 'detail' => 'required', ]); Student::create($request->all()); return redirect()->route('students.index')->with('success','Student created successfully.'); } public function show(Student $student) { return view('students.show',compact('student')); } public function edit(Student $student) { return view('students.edit',compact('student')); } public function update(Request $request, Student $student) { $request->validate([ 'name' => 'required', 'detail' => 'required', ]); $student->update($request->all()); return redirect()->route('students.index')->with('success','Student updated successfully.'); } public function destroy(Student $student) { $student->delete(); return redirect()->route('students.index')->with('success','Student deleted successfully.'); } }
Code language: PHP (php)
  1. Create the view Files

You need to create a folder Inside resources -> views as students. Inside that folder, create the following five files.

  1. layout.blade.php
  2. index.blade.php
  3. create.blade.php
  4. edit.blade.php
  5. show.blade.php

resources/views/students/layout.blade.php

<!DOCTYPE html> <html> <head> <title>Laravel 6.0,5.8 CRUD Application - bishrulhaq.com</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="card" style="margin-top: 20px;"> <div class="card-body"> @yield('content') </div> </div> </div> </body> </html>
Code language: HTML, XML (xml)

resources/views/students/index.blade.php

@extends('students.layout') @section('content') <div class="row"> <div class="col-lg-12"> <h2 class="text-center">Simple Student Management CRUD Application</h2> </div> <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;"> <a class="btn btn-success " href="{{ route('students.create') }}"> Add Student</a> </div> </div> @if ($message = Session::get('success')) <div class="alert alert-success"> {{ $message }} </div> @endif @if(sizeof($students) > 0) <table class="table table-bordered"> <tr> <th>No</th> <th>Name</th> <th>Details</th> <th width="280px">More</th> </tr> @foreach ($students as $student) <tr> <td>{{ ++$i }}</td> <td>{{ $student->name }}</td> <td>{{ $student->detail }}</td> <td> <form action="{{ route('students.destroy',$student->id) }}" method="POST"> <a class="btn btn-info" href="{{ route('students.show',$student->id) }}">Show</a> <a class="btn btn-primary" href="{{ route('students.edit',$student->id) }}">Edit</a> @csrf @method('DELETE') <button type="submit" class="btn btn-danger">Delete</button> </form> </td> </tr> @endforeach </table> @else <div class="alert alert-alert">Start Adding to the Database.</div> @endif {!! $students->links() !!} @endsection
Code language: HTML, XML (xml)

resources/views/students/create.blade.php

@extends('students.layout') @section('content') <div class="row"> <div class="col-lg-12"> <h2 class="text-center">Add Student</h2> </div> <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;"> <a class="btn btn-primary" href="{{ route('students.index') }}"> Back</a> </div> </div> @if ($errors->any()) <div class="alert alert-danger"> <strong>Oops!</strong> There were some problems with your input.<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form action="{{ route('students.store') }}" method="POST"> @csrf <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Name:</strong> <input type="text" name="name" class="form-control" placeholder="Name"> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Detail:</strong> <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12 text-center"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> @endsection
Code language: HTML, XML (xml)

resources/views/students/edit.blade.php

@extends('students.layout') @section('content') <div class="row"> <div class="col-lg-12"> <h2 class="text-center">Edit Student</h2> </div> <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;"> <a class="btn btn-primary" href="{{ route('students.index') }}"> Back</a> </div> </div> @if ($errors->any()) <div class="alert alert-danger"> <strong>Whoops!</strong> There were some problems with your input.<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form action="{{ route('students.update',$student->id) }}" method="POST"> @csrf @method('PUT') <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Name:</strong> <input type="text" name="name" value="{{ $student->name }}" class="form-control" placeholder="Name"> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Detail:</strong> <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $student->detail }}</textarea> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12 text-center"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> @endsection
Code language: HTML, XML (xml)

resources/views/students/show.blade.php

@extends('students.layout') @section('content') <div class="row"> <div class="col-lg-12"> <h2 class="text-center">Show Student</h2> </div> <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;"> <a class="btn btn-primary" href="{{ route('students.index') }}"> Back</a> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Name:</strong> {{ $student->name }} </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Details:</strong> {{ $student->detail }} </div> </div> </div> @endsection
Code language: HTML, XML (xml)

Finally, Laravel CRUD Application is ready to run. Type the following command in your terminal to run the application.

php artisan serve
Code language: PHP (php)

Hope this tutorial helps you! Feel free to drop your opinion at the comment section.

Categories
Laravel

Import, Export from Excel to Database in Laravel 5.8, 5.7, 5.6.

This tutorial is created to Import, Export data from an excel sheet to database in Laravel Framework using maatwebsite/excel package. It provides an easy way to import and export using database model. It will work with Laravel 5.8, 5.7, 5.6.

Read Excel files in Laravel
Laravel Import, Export – Excel CSV
  1. Install Laravel

First, let’s install Laravel using the following command (Make sure, You have installed composer in your PC). Click on Install Composer If you haven’t installed Composer on your PC.

composer create-project --prefer-dist laravel/laravel excelApplication
  1. Configure Database Details

You need to create the database at MYSQL and then we need to connect that database to the Laravel project (You can also use phpmyadmin to create the database). Open the .env file inside Laravel project and add the database credentials as below.

.env

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE='Your DB Name' DB_USERNAME='Your DB UserName' DB_PASSWORD='Your DB Password'
Code language: JavaScript (javascript)
  1. Install Maatwebsite/excel Package

Install Mattwebsite/excel package via the composer manager, use the terminal to run the command below.

composer require maatwebsite/excel
Code language: JavaScript (javascript)
  1. Specify the configuration

After installing maatwebsite/excel package, Go to config/app.php file and add the service provider and aliase.

config/app.php

'providers' => [ .... Maatwebsite\Excel\ExcelServiceProvider::class, ], 'aliases' => [ .... 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ],
Code language: PHP (php)

Type the following command to publish the above configuration settings. If you’re prompt with provide tag files, Choose “Provider: Maatwebsite\Excel\ExcelServiceProvider” to publish.

php artisan vendor:publish
Code language: CSS (css)
  1. Create a database model and migration

In this step, weโ€™re going to create a Data model and migration

php artisan make:model Data --migration
Code language: CSS (css)

The migration will be created under “database/migrations”. Edit the file with the code below to create Data Table.

‘date’_create_data_table.php

<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateDataTable extends Migration { public function up() { Schema::create('data', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('data'); } }
Code language: HTML, XML (xml)

Type the following command to run the migration.

php artisan migrate

Open the generated model in “app/Data.php” Now, Write the schema inside Data.php file.

app/Data.php

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Data extends Model { protected $fillable = ['title','description']; }
Code language: HTML, XML (xml)
  1. Create DataController

Type the following command at your terminal to create DataController.php file in controllers

php artisan make:controller DataController
Code language: CSS (css)

app/Http/Controllers/DataController.php

<?php namespace App\Http\Controllers; use App\Data; use Excel; use Illuminate\Http\Request; class DataController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('index'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function downloadData($type) { $data = Data::get()->toArray(); return Excel::create('excel_data', function($excel) use ($data) { $excel->sheet('mySheet', function($sheet) use ($data) { $sheet->fromArray($data); }); })->download($type); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function importData(Request $request) { $request->validate([ 'import_file' => 'required' ]); $path = $request->file('import_file')->getRealPath(); $data = Excel::load($path)->get(); if($data->count()){ foreach ($data as $key => $value) { $arr[] = ['title' => $value->title, 'description' => $value->description]; } if(!empty($arr)){ Data::insert($arr); } } return back()->with('success', 'Insert Record successfully.'); } }
Code language: HTML, XML (xml)

In this step, Go to ‘routes->web.php’ file, add the following line of code.

Route::get('/', 'DataController@index'); Route::get('downloadData/{type}', 'DataController@downloadData'); Route::post('importData', 'DataController@importData');
Code language: PHP (php)
  1. Create the view File

Create index.blade.php in resources/views folder and add the following code.

resources/views/index.blade.php

<html lang="en"> <head> <title>Laravel Import Export to Excel , CSV Example - bishrulhaq.com</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <style> .container{ margin-top: 10%; } </style> <body> <div class="container"> @if ($errors->any()) <div class="alert alert-danger"> <a href="#" class="close" data-dismiss="alert" aria-label="close">ร—</a> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif @if (Session::has('success')) <div class="alert alert-success"> <a href="#" class="close" data-dismiss="alert" aria-label="close">ร—</a> <p>{{ Session::get('success') }}</p> </div> @endif <div class="card"> <div class="card-body"> <h5 class="card-title">Laravel Import Export to Excel , CSV Example</h5> <a href="{{ url('downloadData/xlsx') }}"><button class="btn btn-dark">Download Excel xlsx</button></a> <a href="{{ url('downloadData/xls') }}"><button class="btn btn-success">Download Excel xls</button></a> <a href="{{ url('downloadData/csv') }}"><button class="btn btn-info">Download CSV</button></a> <form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;" action="{{ url('importData') }}" class="form-horizontal" method="post" enctype="multipart/form-data"> @csrf <input type="file" name="import_file" /> <button class="btn btn-primary">Import File</button> </form> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html>
Code language: HTML, XML (xml)

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Categories
Laravel

Facebook Login with Socialite in Laravel 5.8

The tutorial is created to implement facebook login using Socialite in Laravel 6.0, 5.8 , 5.7 and 5.6. Using Facebook Auth to log and register into your Laravel Application. Follow the steps below to implement laravel socialite facebook login.

  1. Install Laravel 5.8

First, let install Laravel 5.8 using the following command (Make sure you have installed composer in your PC). Click on Install Composer If you haven’t installed Composer on your PC.

composer create-project --prefer-dist laravel/laravel facebookAuth
  1. Configure Database Details

You need to create the database at MYSQL and then we need to connect that database to the Laravel project (You can also use phpmyadmin to create the database). Open the .env file inside Laravel project and add the database credentials as below.

.env

DB_CONNECTION=mysql DB_HOST='Your DB Host' DB_PORT='Your DB Port' DB_DATABASE='Your DB Name' DB_USERNAME='Your DB UserName' DB_PASSWORD='Your DB Password'
Code language: JavaScript (javascript)
  1. Add Socialite

Go to the terminal and type the following php artisan command to download Socialite Package.

composer require laravel/socialite
Code language: JavaScript (javascript)

After installing the package , Configure the provider and aliases in “config/app.php”. Edit the file with the code below.

config/app.php

'providers' => [ // Other service providersโ€ฆ Laravel\Socialite\SocialiteServiceProvider::class, ], 'aliases' => [ // Other aliasesโ€ฆ 'Socialite' => Laravel\Socialite\Facades\Socialite::class, ],
Code language: PHP (php)
  1. Get Secret id and key from Facebook Developer Console

In this step, Configure the CLIENT ID and CLIENT SECRET to add facebook a authentication to your laravel project, Lets begin by opening Developer Console and then create a new App by submitting the name and email.

Developer Console
Developer Console

After creating the App, go to Setting->Advanced and set redirect url as shown below.

Developer Console URL
Developer Console URL

Now it’s time to add Facebook Login by navigating to products in the left menu.

Developer Console Product
Developer Console Product

In this Step, Specify Auth redirect url facebook login->setting and set valid auth redirect url.

Developer Console Auth
Developer Console Auth

After successfully configuring the app on facebook developer console, Set the client id and client secret in config/service.php as shown below

config/service.php

'facebook' => [ 'client_id' => 'xxxx', 'client_secret' => 'xxx', 'redirect' => 'https://bishrulhaq.com/callback/facebook', ],
Code language: PHP (php)
  1. Create route, controller and model

In this step, Go to app/User.php file and add the following line of code.

app/User.php

protected $fillable = ['name', 'email', 'password', 'provider', 'provider_id' ];
Code language: PHP (php)

In this step, Go to app/database/create_users_table.php and add the code below

app/database/create_users_table.php

<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique()->nullable(); $table->string('provider'); $table->string('provider_id'); $table->timestamp('email_verified_at')->nullable(); $table->string('password')->nullable(); $table->rememberToken()->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
Code language: HTML, XML (xml)

Now it’s time to run Laravel Default Auth by typing the command at your terminal.

php artisan make:auth
Code language: CSS (css)

Next, You need to type the following command to run the migration.

php artisan migrate

If you encounter any errors while migrating the table. Add String length under boot method at app/providers/AppServiceProvider.php file and re-run the migration.

use Illuminate\Support\Facades\Schema; function boot() { Schema::defaultStringLength(191); }
Code language: CSS (css)

In this step, Go to ‘routes->web.php’ file, add the following line of code.

routes->web.php

Route::get('/auth/redirect/{provider}', 'AuthController@redirect'); Route::get('/callback/{provider}', 'AuthController@callback');
Code language: PHP (php)

Create AuthController by typing the following command.

php artisan make:controller AuthController
Code language: CSS (css)
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator, Redirect, Response, File; use Socialite; use App\User; class AuthController extends Controller { public function redirect($provider) { return Socialite::driver($provider)->redirect(); } public function callback($provider) { $getInfo = Socialite::driver($provider)->user(); $user = $this->createUser($getInfo, $provider); auth()->login($user); return redirect()->to('/home'); } function createUser($getInfo, $provider) { $user = User::where('provider_id', $getInfo->id)->first(); if (!$user) { $user = User::create([ 'name' => $getInfo->name, 'email' => $getInfo->email, 'provider' => $provider, 'provider_id' => $getInfo->id ]); } return $user; } }
Code language: HTML, XML (xml)
  1. Edit the View

Go to Resources/Views/Auth/login.blade.php and add facebook social login button under the login area.

Resources/Views/Auth/login.blade.php

<hr> <div class="form-group row mb-0"> <div class="col-md-8 offset-md-4"> <a href="{{ url('/auth/redirect/facebook') }}" class="btn btn-primary"><i class="fa fa-facebook"></i> Facebook</a> </div> </div>
Code language: HTML, XML (xml)

Finally, Laravel Facebook Auth Application is ready to run. Type the following command in your terminal to run the application.

php artisan serve

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Categories
JS

JSON in JavaScript

This tutorial is created to provide you with an introduction to working with JSON (JavaScript Object Notation) in JavaScript. JSON is mostly used with AJAX (Asynchronous JavaScript) and XML. It’s a lightweight format to serialize and transmit structured data over a network connection.

JSON for JavaScript is generally used in some of the following scenarios :

  • Data Storage (Storing Data).
  • Data Analysis
  • Data transfer from user / server to relevant medium.
Json
  • Keys and Values

JSON consist of two primary parts as key and value. Together they make a key/value pair.

  1. Key : It’s always a string enclosed in quotation marks.
  2. Value : It can be a string, number, boolean expression, array, or object.
  3. Key/Value Pair : It follows a specific syntax, with the key followed by a colon followed by the value. Key/value pairs are comma separated.

Syntax & Structure

{ "key": "value" }
Code language: JSON / JSON with Comments (json)

JSON array consist of many data types. Here is an example of an array with different data type:

[ "Bishrul", // string { // object "id": "01", "name": "BH" }, True, // Boolean 5.7 // number ]
Code language: JSON / JSON with Comments (json)

The following data types can be used with JSON:

  • Strings (in double quotes)
  • Arrays
  • Numbers
  • Objects
  • Booleans (true or false)
  • null
  • Working with JSON in JavaScript

Here’s the JSON data we’ll use in this example:

{ "details" : [ { "name" : "Bishrul Haq", "born" : "1994" }, { "name" : "Bill Gates", "born" : "1955" }, { "name" : "Dennis Ritchie", "born" : "1941" }, ] }
Code language: JSON / JSON with Comments (json)

In this step, We’ll use JavaScript to take the above JSON data and output it to the HTML document as shown below :

<!doctype html> <title>JSON Sample | BH</title> <script> function displaydetails() { // JSON Details let data = { "details": [ { "name": "Bishrul Haq", "born": "1994" }, { "name": "Bill Gates", "born": "1955" }, { "name": "Dennis Ritchie", "born": "1941" }, ] } let output = "<h1>Detaills</h1>"; output += "<ul>"; // Loop through the artists for (let i in data.details) { output += "<li>" + data.details[i].name + " (Born: " + data.details[i].born + ")</li>"; } output += "</ul>"; document.getElementById("detailList").innerHTML = output; } window.onload = displaydetails; </script> <!-- output --> <div id="detailList"></div>
Code language: HTML, XML (xml)
  • Convert a JavaScript object into a String

The JSON.stringify() function converts JS object into a string. Strings are lightweight and it’s faster to use between client to server.

Let’s assign the JSON.stringify() method to following variable output.

<!doctype html> <title>JSON Sample | BH</title> <script> function displaydetails() { // JSON Details let data = { "details": [ { "name": "Bishrul Haq", "born": "1994" }, { "name": "Bill Gates", "born": "1955" }, { "name": "Dennis Ritchie", "born": "1941" }, ] } let output = JSON.stringify(data); document.getElementById("detailList").innerHTML = output; } window.onload = displaydetails; </script> <!-- output --> <div id="detailList"></div>
Code language: HTML, XML (xml)

To convert a JSON String back into a function, We use JSON.parse() function.It helps to access the data like a regular JavaScript object.

let output = JSON.parse(output);
Code language: JavaScript (javascript)
  • Nested JSON Objects

In this Step, We’ll use a JSON file with Deeper Nesting. Not only does this file have details about users, but each user has a number of skills. So we need to loop through the users, and also loop through each users’ skills.

<!doctype html> <title>JSON Example | BH</title> <script> function displayUsers() { // JSON data let data = { "users": [ { "name": "Jhon", "born": "1994", "skills": [ { "skillname": "Java Programming", "experience": "2 Years" }, { "skillname": "Laravel", "experience": "1 Years" }, { "skillname": "React Native", "experience": "3 Years" } ] }, { "name": "Bishrul Haq", "born": "1994", "skills": [ { "skillname": "Android Development", "experience": "2 Years" }, { "skillname": "Angular JS", "experience": "1 Years" } ] }, ] }; let output = "<h1>Users</h1>"; // Loop through the users for (let i in data.users) { output += "<h2>" + data.users[i].name + "</h2>"; output += "<ul>"; // Loop through the user for their skills for (let j in data.users[i].skills) { output += "<li>" + data.users[i].skills[j].skillname; } output += "</ul>"; } document.getElementById("usersList").innerHTML = output; } window.onload = displayUsers; </script> <!-- Output --> <div id="usersList"></div>
Code language: HTML, XML (xml)

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Categories
JS

How to Get, Set and Delete Div Background Image using jQuery?

This tutorial is created to Set, Get and Delete background image. In this tutorial, You’ll learn to Get, Set and Remove the background image using jQuery.

  1. Get Background Image

You can use the below code for getting the background image in jQuery with fade out effect.

$("#btn-get").click(function () { var bg = $('#bg-img').css('background-image'); bg = bg.replace('url(', '').replace(')', ''); alert(bg); });
Code language: JavaScript (javascript)
  1. Set Background Image

You can use the below code for setting the background image using the jQuery CSS property with fade in effect.

$("#btn-set-fade").click(function () { var img = 'http://localhost/BH/assets/images/main/blog-image25.jpg'; $('#bg-img').css('background-image', "url(" + img + ")").fadeIn('slow'); });
Code language: JavaScript (javascript)
  1. Remove Background Image

You can use the below code for removing the background image using the jQuery CSS property.

$("#btn-remove-fade").click(function () { $('#bg-img').fadeOut('fast', function () { $('#bg-img').css('background-image', 'none'); }); });
Code language: JavaScript (javascript)
  1. Here’s an Example

You’ll find all the above get , set and remove background image in a div separate JS functions using the jQuery css property.

index.html

<html> <head> <title>How to Get, Set and Delete Div Background Image using jQuery | BH</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> .container-fluid { margin: 30px; } .btn-group{ margin-bottom:20px; } .border-heading{ padding: 10px; border-radius: 5px; border: 2px solid saddlebrown; } </style> </head> <body> <div class="container-fluid"> <div class="text-center"> <div class="btn-group" role="group" aria-label="Basic example"> <button id="btn-get" type="button" class="btn btn-secondary">Get background image</button> <button id="btn-remove-fade" type="button" class="btn btn-secondary">Remove background image</button> <button id="btn-set-fade" type="button" class="btn btn-secondary">Set background image</button> </div> </div> <div id="bg-img"style="background-image: url('https://bishrulhaq.com/assets/images/main/blog-image26.jpg'); width: 1395px; height: 573px;"> <p class="text-center border-heading"><b>Hello World! It's BH</b></p> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"crossorigin="anonymous"></script> <script> $(function () { $("#btn-set-fade").click(function () { var img = 'https://bishrulhaq.com/assets/images/main/blog-image25.jpg'; $('#bg-img').css('background-image', "url(" + img + ")").fadeIn('slow'); }); $("#btn-remove-fade").click(function () { $('#bg-img').fadeOut('fast', function () { $('#bg-img').css('background-image', 'none'); }); }); $("#btn-get").click(function () { var bg = $('#bg-img').css('background-image'); bg = bg.replace('url(', '').replace(')', ''); alert(bg); }); }); </script> </body> </html>
Code language: HTML, XML (xml)

Hope this tutorial helped you! Feel free to drop your suggestions and opinions at the comment section below.