Shehroz Azam – Linux Hint https://linuxhint.com Exploring and Master Linux Ecosystem Thu, 11 Mar 2021 05:59:08 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.2 Vue Computed Deep Structures https://linuxhint.com/vue-computed-deep-structures/ Mon, 08 Mar 2021 18:02:37 +0000 https://linuxhint.com/?p=93479 When it comes to the computation of nested or deep data types like arrays or objects, Vue.js or any other programming language does not automatically detect the hierarchical change in the data. However, we all know that Vue.js provides the watch and computed properties to perform some change variables. But when it comes to nested data changes, Vue.js does not detect that. This post will learn to perform some changes by watching the nested data of arrays or objects.

Before learning about watching nested data in Vue.js, let’s first understand how the watch property works?

Watch Property

The watch property is used to watch a variable and allows the user to perform some desired tasks on the variable’s change.

Example: Watch a Variable

For example, at the change of some variable, we want to console something. The syntax for writing such code in Vue will go like this:

<template>

  <div class="test">

    <h1>This is a testing page</h1>

    <button @click="boolVar=!boolVar">Click</button>

  </div>

</template>

<script>

export default {
  name: "Test",
  data(){
    return{
      boolVar: true
    }
  },
  watch:{
    boolVar(){
      console.log("Button clicked.")
    }
  }
};

</script>

After writing the above code, the web page would be like this.

If we click on the button, the state of the “boolVar” should be altered due to the button’s on-click attribute, and the watch should automatically detect the change in “boolVar” and display the message string on the console.

It worked perfectly fine; the message “Button clicked” is displayed on the console.

But, the watcher fails to detect the change and does not get fired when it comes to watching the arrays or objects. Let’s see a demonstration of that.

Example: Watching an Object

Suppose we have an object in our component, and we want to display the change that happened in the object’s property. In the example given below, I have created an object with the name of “objVar,” which contains two key-value pairs, “item” and “quantity”. I have created a button where I am adding “1” to the template tag’s quantity. Lastly, I am watching the “objVar” object in the watch property and displaying a console message.

<template>

  <div class="test">

    <h1>This is a testing page</h1>

    <button @click="objVar.quantity=objVar.quantity+1">Click</button>

  </div>

</template>

<script>

export default {
  name: "Test",
  data(){
    return{
      objVar: {
        item: "Item1",
        quantity: 1
      }
    }
  },
  watch:{
    objVar(){
      console.log("Button clicked & Quantity = " + this.objVar.quantity)
    }
  }
};


</script>

Now, this code is supposed to display the change in the quantity of the object. But, when we execute the code and click the button on the web page:

You can see in the above gif; nothing is happening in the console.

The reason behind this is that the watcher does not look deep into the values of the objects, and this is the real problem to which we are going to solve now.

Vue.js provides the deep property for watching deep down into the values of objects and arrays. The syntax for using the deep property and watching the nested data is as follows:

<script>

export default {
  name: "Test",
  data(){
    return{
      objVar: {
        item: "Item1",
        quantity: 1
      }
    }
  },
  watch:{
    objVar: {
      deep: true,
      handler(){
        console.log("Button clicked & Quantity = " + this.objVar.quantity)
      }
    }
  }
};

</script>

In this syntax, we have set the deep property to true and rearranged the handler() function.

Now, after changing the code, if we reload the web page and click on the button:

Here you can see that the watcher is working and displaying the message in the console.

Conclusion

After reading this post, watching and computing deep or nested data structures in Vue.js is not difficult anymore. We have learned how to watch the change of a value in an object or array and execute some tasks with the help of the “deep” property of Vue.js.

]]>
Vue Computed Property not updating; Troubleshooting Steps https://linuxhint.com/troubleshoot-vue-computed-property-not-updating/ Mon, 08 Mar 2021 17:47:30 +0000 https://linuxhint.com/?p=93468 Vue.js is a very popular JavaScript library that is known for its reactivity, flexibility, and intuitive API. However, reactivity and flexibility come with some drawbacks, leading to the developer’s performance or a headache. The computed property is a very famous and most known feature of Vue.js, which is used to update some variable or perform some calculation depending upon some other variable’s updation.

This post will try to troubleshoot the problems that occurred when the computed property does not work or update what we want. Let’s have a look at the scenarios, what might go wrong, and Vue Computed Property not updating.

Scenario # 1:

First of all, make sure you did not make any logical error like implementing the wrong logic. To avoid the possible logical errors, check the following things:

  • Verify that variable names are correct.
  • You are taking care of the scopes of the variable using “this”.

Scenario # 2:

The second thing you might have mistaken in the computed property is that you are not caring about the Computed property’s side effects like editing some data inside a computed property or calling other functions. For example, reversing the array within a computed property.

Suppose we have an array in our component.

  data(){
    return{
      arrVar:[1,2,3]
    }
  },

In the computed property, we are reversing the array.

  computed:{
    arrayReverse(){
      return this.arrVar.reverse();
    }
  }

But, when we run the project, it will show an error of ‘Unexpected side effect in “arrayReverse” computed property.’ because it will always do the same task again and again and reverse the original array every time.

So, try to avoid data manipulation in the computed property, and it will work perfectly fine for you.

Scenario # 3:

Another scenario could be that the computed property is stuck in an infinite loop, and it keeps on re-computing something. Since computed property watches every variable included in the computed property and reacts or gets recomputed on the change of any variable involved in this property, if you change the state of any variable inside the computed property, the computed property detects the change. It starts to re-compute itself, and it won’t be able to get out of this infinite loop.

These are some of the possible ways which could lead to the computed property not updating problem.

Conclusion

This post has gone through the most common scenarios the developers faced for Vue Computed property not updating and provided profound and to-the-point troubleshooting steps for each scenario. If you still have not found your solution yet, feel free to ask your questions on the Vue community platforms and get your questions answered within no time.

]]>
Vue Computed with Parameter https://linuxhint.com/vue-computed-with-parameter/ Mon, 08 Mar 2021 10:19:47 +0000 https://linuxhint.com/?p=93463 The Computed property is usually used to compute data from some other data. It is known for its reactivity because whenever a variable involved in some computed property gets changed, the whole property gets recomputed.This post will learn to pass the parameter to computed property and see how to use Vue computed with parameter. Before getting started with passing parameters to the computed property, let’s first understand the computed properties by going through the example.

Examples

Suppose we have two variables named “firstName” and “lastName” in our Vue component:

//..
  data(){
    return{
      firstName: "",
      lastName: ""
    }
  },
//..

Computed Property

We want to compute a “fullName” property that will combine the “firstName” and “lastName” and recompute the fullName whenever any of the two variables “firstName” and “lastName” gets changed. So, the computed property for computing the full name would be like this:

//..
  computed:{
    fullName(){
      return this.firstName + ' ' + this.lastName;
    }
  }
//..

Now let’s create some input fields and bind the “firstName” and “lastName” variables to the input fields and also bind the “fullName” property in the ‘p’ tag to view the instant change on the change of the first anime of the last name. The HTML part of this component will be like this:

Alright! After having all this setup, let’s take a look at our webpage.

If you have successfully written the correct code and run it, you should also have the two input fields on your web page. Let’s try to type the first name and last name and see either the “fulName” property gets computed or not.

Here in the screenshot given above, you can witness the marvelous reactivity of Vue.js using the computed property. You can also witness that it is not like watching a single variable and changing some other variable’s value. Still, it is watching each variable included in the computed property and re-computing the “lastName”. Let’s see how we can pass parameters to the computed property and use it.

Pass parameters to the Computed Property

For passing the parameters to the computed property, we just pass the parameters as we do for the function. For example, in the template, when we have bound the variable “lastName,” we want to pass some string, so the template part of our component would be like this:

Now, in the computed property, the passed parameter can be utilized using the following syntax.

 computed:{
    fullName(){
      return message1 => {
        return `${message} ${this.firstName} ${this.lastName}`
      }
    }
  }

This is how we can pass a parameter to the computed and get it in the property and use it.

If we again look at our web page and type the First name and last name, you can have the same functionality and reactivity, but this time, the parameter passed.

This is how simple and easy it is to pass a computed property parameter and use it.

Conclusion:

The computed property is a very powerful feature of Vue.js, and we have learned that it comes in handy when we have to change them when their dependencies get changed. We have learned to pass the parameter and use it in the computed property.

]]>
How to Create and Delete Users on CentOS 8 https://linuxhint.com/how-to-create-and-delete-users-on-centos-8/ Sun, 07 Mar 2021 22:02:00 +0000 https://linuxhint.com/?p=93186

User management is much needed and must-know technique for a Linux server administrator. A Linux administrator often needs to create and grant different privileges and permissions to different users. This post will perform a couple of tasks like creating and deleting the user on the CentOS 8 Operating system.

As you know, the creation and deletion of a user is an administrative type of task, and for performing such tasks, you must log in as a root user or execute all the commands with the sudo privileges. Let’s start and see how to add or create a user in the CentOS 8 system.

Creating a user in CentOS 8

The user can be added or created in the CentOS 8 system using the “adduser” command in the terminal. For example, if we want to create a user with the name “John”, the command would be like this:

$ sudo adduser john


After successfully creating the user, it’s time to assign the password to the newly created user. You can simply assign the password using the “passwd” command:

$ sudo passwd john

After running the above command, it will prompt for the password, so provide the password twice, and the password will be set for the newly created user.

Granting Sudo privileges to the User

Suppose you want to give administrative rights to this newly created user. In that case, you have to add the user in the wheel group (the group which grants sudo privileges to all of its users automatically). To add the user to the wheel group, type the command given below:

$ sudo usermod -aG wheel john

The administrative rights are granted successfully to the newly created user as well. Now let’s see how to delete a user in the CentOS 8 Operating system.

Deletion of a user in CentOS 8

Now, if you want to delete any user from the CentOS 8 Operating system due to any reason, either that user is unnecessary or not needed anymore. For example, if we want to delete the user “john”, we can delete such a user using the “userdel” command:

$ sudo userdel -r john

The “-r” flag in the above-given command is for deleting the user’s home directory. If you do not want to delete the user’s home directory, you can run the above command without the “-r” flag.

This is it; the user is deleted successfully as well from the CentOS 8 Operating system.

Conclusion

This post explains user creation, granting privileges to the user, and deleting a user from the CentOS 8 Operating system. Users with different privileges have a lot to do while managing the Linux servers, and after reading this post, you can manage the users well on CentOS 8 Operating system.

]]>
How to Install Apache Cassandra on CentOS 8 https://linuxhint.com/install-apache-cassandra-centos-8/ Sun, 07 Mar 2021 21:32:18 +0000 https://linuxhint.com/?p=93229

Apache Cassandra is a very popular NoSQL database created by Facebook Inc. but later owned by Apache Foundation. It was designed and built for the ease of scalability and management of large databases. Apache Cassandra is a must-go database Management System for you if your concern is high availability and scalability. This post will take you to a step-by-step guide on installing and configuring Apache Cassandra on CentOS 8 Operating system.

Installation of Apache Cassandra on CentOS 8

Apache Cassandra can be installed by downloading the RPM package through the official repository of Apache Cassandra.

But, before getting started with the installation and configuration of Apache Cassandra on CentOS 8, we need to have OpenJDK 8 installed on the CentOS 8 system.  You can verify the installed version of Java, either it is installed or not on your system, by typing the command given below:

$ java -version

If it is not installed on your system, you can install it using the procedure given below or pre-installed on your system; you can skip the installation part of OpenJDK on CentOS 8.

Install Open JDK on CentOS 8

OpenJDK is available in CentOS 8’s official repository and can easily be installed.

First of all, update the system’s package repository cache:

$ sudo dnf makecache

After updating your CentOS 8’s system repository cache, update it:

$ sudo dnf upgrade


After upgrading the system’s existing packages, you can move forward to installing OpenJDK 8 on CentOS 8 for Apache Cassandra. To install OpenJDK from CentOS 8 official repository, type the command given below in the terminal:

$ sudo dnf install java-1.8.0-openjdk-devel


Type “y” and hit “Enter”.


After installing OpenJDK, verify by typing the command given below:

$ java -version


You can witness that the installed version of OpenJDK is 1.8.0. Let’s move ahead.

Install Apache Cassandra

To install Apache Cassandra, we have to add the repository of Apache Cassandra to the system.

To add Apache Cassandra repository to the CentOS 8 system. Create a “/etc/yum.repos.d/cassandra.repo” file by typing the command:

$ sudo nano /etc/yum.repos.d/cassandra.repo

In the newly created Cassandra repository file, paste the content given below in that file.

[cassandra]
name=Apache Cassandra
baseurl=https://www.apache.org/dist/cassandra/redhat/311x/
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://www.apache.org/dist/cassandra/KEYS


After adding the above content, save the file and exit using the keyboard shortcut keys (CTRL+S) and (CTRL+X).

Now, install the Apache Cassandra by typing the command given below:

$ sudo dnf install cassandra -y

Apache Cassandra is installed on CentOS 8. Now, Apache Cassandra’s service won’t automatically start. You first have to enable it by typing the command given below:

$ sudo systemctl enable cassandra

Then, start the service by typing the following command:

$ sudo systemctl start cassandra

Now, in order to verify, check the status of the Apache Cassandra service by typing the command given below:

$ sudo systemctl status cassandra

At this stage, Apache Cassandra is successfully installed and running perfectly fine on the CentOS 8 machine. Let’s configure it and log in to its CQL shell.

How to configure Apache Cassandra on CentOS 8

Apache Cassandra has its own CQL (Cassandra Query Language), just like SQL. To login to Cassandra’s command-line utility, known as CQL shell or “cqlsh”, we have to install an appropriate python interpreter first. To install Python 2 and access the CQL shell on CentOS 8, type the command given below:

$ sudo dnf install python2

Type “y” and press “Enter”.

Once Python2 is installed, log in to the CQL shell using the command line utility of Cassandra by typing the following command in CentOS 8 terminal:

$ cqlsh

You can witness in the screenshot; we have successfully logged in to the CQL shell.

This is how simply we can configure the Apache Cassandra on CentOS 8 and start using it.

Conclusion

Apache Cassandra Database is used by many big names in the industry like Facebook, Instagram, Netflix, and Reddit. This post contains a clear understanding and profound guide on how to install and configure Apache Cassandra on CentOS 8.

]]>
How to Install Slack on CentOS 8 https://linuxhint.com/install-slack-centos-8/ Sun, 07 Mar 2021 21:03:16 +0000 https://linuxhint.com/?p=93276

Slack is a very popular application used for communicating and collaborating with the team members of a company or an organization. Slack provides various workspaces for teammates to connect with each other at a single platform known as a channel. You can have an individual or group discussion in a channel, share files and images, and have a video or audio call for quick collaboration with your teammates and make quick decisions.

Slack is a cross-platform collaborative application, and it can be installed on all major Operating systems like Windows, macOS, and Linux Operating systems. We will learn the installation of Slack on the CentOS 8 system in this post. Let’s get started.

Installation of Slack on CentOS 8

Installing the Slack application on CentOS 8 is as easy as installing any other application. We will learn to install the Slack application on CentOS 8 by using the .RPM file.

Install Slack using the RPM file on CentOS 8

First of all, and as always, update your system’s metadata cache:

$ sudo dnf makecache

And update the system’s DNF package repository as well:

$ sudo dnf upgrade

<

To install Slack on CentOS 8, we need to download Slack’s RPM file for CentOS 8 by visiting Slack’s official website. Visit the link given below:

https://slack.com/intl/en-pk/downloads/linux

Click on the “DOWNLOAD .RPM (64-BIT)” button.


Save the file, and Slack starts to download.

Once the RPM file is downloaded, open the directory in which the RPM file of the Slack application is downloaded.

Open the directory in the terminal by right-clicking in the directory and selecting the “Open in terminal” option.


A terminal window will open like this.


Now, type the following command in the terminal and make sure you are in the Downloads directory or the directory in which the RPM file of Slack is downloaded:

$ sudo dnf localinstall ./slack-*.rpm

Type “y” and hit “Enter”.

At this moment, Slack is installed on your CentOS 8 system.

Launch the Slack Application

After successfully installing Slack on CentOS 8, you can launch the slack on CentOS by searching for “Slack” in the activities and clicking on the Slack icon from the search results.

Here you can see the login screen of Slack on your CentOS 8 machine. Sign In to Slack and get started.

This is how you can install slack on your CentOS 8 machine.

How to update Slack on CentOS 8

Slack can easily be updated if you find its new version is released by typing the command given below.

$ sudo dnf update slack

How to uninstall Slack from CentOS 8

If you want to uninstall or remove Slack from your CentOS 8 system due to any reason, You can do so by typing the command given below in the terminal of CentOS 8.

$ sudo dnf remove slack

Type “y” to continue the uninstallation process of Slack.

Slack will be successfully removed or uninstalled from your CentOS 8 machine.

Conclusion

Slack is rapidly growing, and many big organizations and companies are using it to collaborate and have quick decisions. In this post, we have provided you an easy-to-understand guide on installing Slack on CentOS 8 by merely downloading the RPM file of the Slack application for Red Hat enterprise Operating systems and installing it by running one simple command. If you want to learn more about Slack, feel free to visit the official Help Center of Slack on their official website.

]]>
How to Install WireGuard VPN on CentOS 8 https://linuxhint.com/install-wireguard-vpn-centos/ Fri, 26 Feb 2021 17:42:39 +0000 https://linuxhint.com/?p=91509

WireGuard is a popular point-to-point open-source communication protocol that is used to create a secure and fast Virtual Private Network tunnel. This VPN was designed for use in the Linux Kernel. WireGuard is a lightweight VPN that provides extremely fast speeds to users.

This article shows you how to install and set up WireGuard on your CentOS 8 system. The installation and setup of WireGuard are much easier than the already-existing VPNs, like OpenVPN, and this is a major reason behind its growing popularity in the Linux community.

Overview

This article is comprised of two sections:

  • In the first section, we will install and configure a CentOS 8 machine that will act as a WireGuard VPN Server.
  • In the second section, we will install and configure a CentOS 8 machine that will act as a WireGuard VPN Client.

Installing and Configuring WireGuard on a CentOS 8 Server

In this section, we will set up a CentOS 8 machine that will act as a server by installing WireGuard.

Step 1: Add EPEL and Elrepo Repositories

To get started with installing WireGuard on CentOS 8, first, add the EPEL and Elrepo repositories to install the kernel modules and WireGuard tools.

$ sudo dnf install epel-release elrepo-release -y

Now, after installing the required repositories, install the kernel modules and WireGuard tools.

Step 2: Install Kernel Modules and WireGuard Tools

The kernel modules and WireGuard tools can be installed quickly from the EPEL and Elrepo repositories by issuing the following command:

$ sudo dnf install kmod-wireguard wireguard-tools

When you are prompted for permission to import and add the GPG keys to the CentOS 8 system, allow this action by typing “Y” and hitting “Enter.”

After successfully installing the WireGuard tools, we will now perform some configurations.

Step 3: Create Public and Private Keys

First, we will create a new ‘/etc/wireguard’ directory so that we can configure the VPN server in the directory. To create a new ‘/etc/wireguard’ directory in the CentOS 8 system, issue the following command.

sudo mkdir /etc/wireguard

After creating the directory, create the public and private keys using the “wg” and “tee” command-line tools. The command for creating private and public keys is as follows.

$ wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey

The generated key will be printed upon execution of the above command.

Step 4: Configuration of Tunnel Device for Routing VPN Traffic

To set up a device, create a configuration file in the ‘/etc/wireguard’ directory and open the file using the nano editor.

Before creating the configuration file, obtain the Private Key using the following command.

$ sudo cat /etc/wireguard/privatekey

Save the private key somewhere; you will need this key later in the configuration file.

Now, create the “wg0.conf” file.

$ sudo nano /etc/wireguard/wg0.conf

Add the content given below to the “/etc/wireguard/wg0.conf” file.

[Interface]

## IP Address of VPN server ##
Address = 192.168.18.200/24

## Save the configuration when a new client will add ##
SaveConfig = true

## port number of VPN server ##
ListenPort = 51820

## Private Key of VPN Server ##
PrivateKey = SERVER_PRIVATE_KEY

## Command to be executed before starting the interface ##
PostUp     = firewall-cmd --zone=public --add-port 51820/udp && firewall-cmd --zone=public --add-masquerade

## Command to be executed before turning off the interface ##
PostDown   = firewall-cmd --remove-port 51820/udp --zone=public && firewall-cmd --remove-masquerade --zone=public

This configuration file contains the following key terms:

  • Address – the private IP address for the Interface (wg0).
  • SaveConfig = true – saves the state of the interface on restart or shutdown of the server.
  • ListenPort – the port where the WireGuard daemon listens.
  • PrivateKey – the key that we have just generated.
  • PostUp – this command will be executed before firing up the interface
  • PostDown – this command will be executed before turning off the interface.

Now that you understand the Configuration file pretty well, you can save the file and exit using the keyboard shortcuts (CTRL + S) and (CTRL + X).

Step 5: Set Privileges of Configuration and “privatekey” File

Now, we will make the VPN server a bit more secure. A basic user should not have the privileges to read the configuration file and the ‘privatekey’ file. To provide access to these files, we will change the mode of these two files to 600. The command for setting the permissions is given below.

$ sudo chmod 600 /etc/wireguard/privatekey

$ sudo chmod 600 /etc/wireguard/wg0.conf

After finalizing the permissions, we will fire up the interface (wg0) using the wg-quick command-line tool.

Step 6: Start the Interface

To fire up the interface, issue the command given below:

$ sudo wg-quick up wg0

If you have obtained the output shown in the screenshot above, you have successfully started the interface. We will now check the status of the interface.

$ sudo wg

Enable the interface to auto-start the interface on boot of the CentOS 8 server.

$ sudo systemctl enable wg-quick@wg0

At this stage, the server setup has been completed. Now, if you want to set up this VPN server for NAT, you will need to enable IPv4 forwarding.

Step 7: Enable IPv4 Forwarding

To enable IPv4 forwarding for the NAT, create a “99-custom.conf” file in the “/etc/sysctl.d” directory using the nano editor.

$ sudo nano /etc/sysctl.d/99-custom.conf

Add the following content to the “/etc/sysctl.d/99-custom.conf”

## for enabling IPv4 forwarding ##
net.ipv4.ip_forward = 1

To enable IPv6 forwarding, add the following content to the “/etc/sysctl.d/99-custom.conf” file, as well.

## for enabling IPv6 forwarding ##
net.ipv6.conf.all.forwarding = 1

After enabling IPv4 forwarding, save the file and exit using the shortcuts (CTRL +S) and (CTRL + X).

Let us now move on to set up the WireGuard Client machine.

Installation and Configuration of WireGuard VPN on CentOS 8 Client

In this section, we will set up a CentOS 8 machine that will act as a client. The process of installing and configuring the WireGuard VPN client will be nearly the same as it was for the WireGuard VPN server.

Step 1: Add EPEL and Elrepo Repositories

First, we will add the EPEL and Elrepo repositories to install the kernel modules and WireGuard tools:

$ sudo dnf install epel-release elrepo-release -y

Now, after installing the required repositories, we will install the kernel modules and WireGuard Tools.

Step 2: Install Kernel modules and WireGuard Tools

The kernel modules and WireGuard tools can now be installed from the EPEL and Elrepo repositories by issuing the following command.

$ sudo dnf install kmod-wireguard wireguard-tools

When you are asked for permission to import and add the GPG keys to the CentOS 8 system, allow the changes by typing “Y” and hitting “Enter.”

After the WireGuard tools have been successfully installed, the CentOS 8 Client machine needs to be configured, as well.

Step 3: Create Public and Private Keys

In this step, we will create a new ‘/etc/wireguard’ directory in the Client machine. To create the new ‘/etc/wireguard’ directory in your CentOS 8 system, enter the following command.

sudo mkdir /etc/wireguard

After creating the directory, create the public and private keys using the “wg” and “tee” command-line tools. The command for creating private and public keys is provided below.

$ wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey

The generated keys will now be printed.

Step 4: Configuration for Routing VPN Traffic

In this step, we will create a configuration file in the ‘/etc/wireguard’ directory and open it using the nano editor.

Before creating the configuration file, get the Private key using the following command.

$ sudo cat /etc/wireguard/privatekey

Save the private key somewhere; you will need it later in the configuration file.

Now, create the “wg0.conf” file.

$ sudo nano /etc/wireguard/wg0.conf

Add the content given below to the “/etc/wireguard/wg0.conf” file

[Interface]
## Private Key of VPN Client ##
PrivateKey = 8D8puLQCbUw+51wPE3Q7KutGxQhUvsy+a+DBgamb+3o=

## IP address of VPN Client ##
Address = 192.168.18.201/24

[Peer]
## Public Key of CentOS 8 VPN Server ##
PublicKey = VWndJ4oB7ZJwC/7UOm++OLDrbAxMPsR2yd0cl3sEkUI=

## set ACL ##
AllowedIPs = 0.0.0.0/0

## IP address and Port of CentOS 8 VPN Server ##
Endpoint = 192.168.18.200:51820

The configuration file contains the following key terms:

  • PrivateKey – the key generated on the client machine.
  • Address – the IP address for the Interface (wg0).
  • PublicKey – the public key of the VPN server machine to which we want to connect.
  • AllowedIPs – all allowed IP addresses for traffic flow using the VPN.
  • Endpoint – we will provide the IP address and port number of the CentOS 8 server machine to which we want to connect.

We have now configured the client machine, as well. Save the file and exit using the keyboard shortcuts (CTRL + S) and (CTRL + X).

Step 5: Set Privileges of Configuration and “privatekey” File

Now, we will change the mode and set the privileges of the configuration file and “privatekey” file to 600. Enter the following command to set the permissions.

$ sudo chmod 600 /etc/wireguard/privatekey

$ sudo chmod 600 /etc/wireguard/wg0.conf

Now that we have finalized the permissions, we can fire up the interface (wg0) using the “wg-quick” command-line tool.

Step 6: Start the Interface

To fire up the interface, issue the command given below:

$ sudo wg-quick up wg0

We have now successfully started the interface. Next, we will check the status of the interface.

$ sudo wg

Enable the interface to auto-start the interface on boot of the CentOS 8 server.

$ sudo systemctl enable wg-quick@wg0

At this stage, the client is also set up.

Step 7: Add IP Address and Public Key of Client to CentOS 8 Server

The final step is to add the IP address and public key of the VPN client machine to the configuration file of the CentOS 8 WireGuard VPN server machine.

Return to the server machine and add the following content to the “/etc/wireguard/wg0.conf” file.

[Peer]
## Public Key of VPN Client ##
PublicKey = dmfO9pirB315slXOgxXtmrBwAqPy07C57EvPks1IKzA=

## IP Address of VPN Client ##
AllowedIPs = 192.168.10.2/32

After updating the configuration file of the VPN server, save the file and exit using the keyboard shortcuts (CTRL + S) and (CTRL + X).

The tunnel has now been established, and all the traffic will be passed through the CentOS 8 WireGuard VPN server.

Step 8: Verify Tunnel Connection

To verify that the CentOS 8 WireGuard VPN server has been installed and configured properly, issue the command given below to verify that traffic is flowing through the configured WireGuard VPN Server.

$ sudo wg

And that is it! You have configured and established the WireGuard VPN server successfully.

Conclusion

This article showed you how to install and configure WireGuard VPN on your CentOS 8 machine and set the system up as a VPN server. We also showed you how to set up a CentOS 8 WireGuard VPN Client and configure the client to route the traffic through the WireGuard VPN server.

]]>
How to Install Webmin on CentOS 8 https://linuxhint.com/install-webmin-centos/ Thu, 25 Feb 2021 06:57:56 +0000 https://linuxhint.com/?p=91490
Webmin is a popular open-source web-based control panel that is used for configuring and managing Unix-like operating systems. This tool allows you to manage your Linux server, and you can use the web interface for managing and creating files, directories, users, and groups. Webmin also allows users to manage services such as FTP, mail, and web servers. This article covers the installation procedure of Webmin on CentOS 8.

Installation of Webmin on CentOS 8

The process of installing Webmin on CentOS 8 is quite straightforward. You can install Webmin on CentOS 8 machine using the RPM package in only four simple steps.

Step 1: Update CentOS8 System

First, update the DNF package repository cache and make sure that the system is up-to-date. To update the DNF repository cache, issue the following command.

$ sudo dnf makecache

To upgrade the system, enter the command given below.

$ sudo dnf upgrade

Now, after updating the DNF repository cache and installed packages, we will download the Webmin RPM package and then install it using the dnf package manager.

Step 2: Download Webmin RPM Package

To download the RPM package of Webmin, you can either:

Download the RPM file from the official website of Webmin by visiting the link below:
https://www.webmin.com/download.html

Or, download the RPM package of Webmin by issuing the following command in the CentOS 8 terminal.

$ wget http://prdownloads.sourceforge.net/webadmin/webmin-1.970-1.noarch.rpm

After downloading the Webmin RPM package, download and install the optional dependencies by entering the command given below.

$ sudo dnf install perl perl-Net-SSLeay openssl perl-Encode-Detect

Once the optional dependencies of Webmin have been installed, we will install the downloaded RPM package of Webmin.

Step 3: Install Webmin Using the RPM package

To install Webmin using the downloaded RPM file, issue the following command.

$ sudo rpm -Uvh webmin-1.970-1.noarch.rpm

Now, the latest stable version of Webmin has been installed.

You can start using the Webmin Control panel by going to a browser and visiting the localhost with the port 10000 since the default port of Webmin is 10000.

https://localhost:10000

To connect to the Webmin remotely, you will need to configure the Firewall settings for Webmin.

Step 4: Configuring Firewall Settings for Webmin

Since Webmin listens on port 10000 by default, we will need to add port 10000 to the firewall. To allow port 10000, enter the following command:

$ sudo firewall-cmd --add-port=10000/tcp --zone=public --permanent

Once the firewall has been configured, you should now be able to access the web interface remotely.

Step 5: Start Using Webmin

To access Webmin from any other system, you can access it by typing the server IP address, along with the port number 10000, in any browser of your choice.

Conclusion

This article showed you how to install Webmin on CentOS 8. We also showed you how to configure the CentOS 8 system firewall to access the Webmin portal remotely. From the Webmin portal, you can manage and configure the Linux server according to your needs and preferences.

]]>
How to Install and Use Curl in Centos 8 https://linuxhint.com/install-use-curl-centos/ Thu, 25 Feb 2021 06:56:14 +0000 https://linuxhint.com/?p=91513
Curl, short for “Client URL,” is a popular command-line utility that is used to transfer data between a server and its client using various protocols, such as HTTP, HTTPS, FTP, SMTP, etc. Curl provides data security and the effortless simultaneous transfer of multiple files. This article covers the installation and usage processes of Curl on the CentOS 8 operating system.

Installation of curl on CentOS 8

The Curl package is available in the official package repository of CentOS 8, and it can easily be installed.

First, ensure that your CetnOS 8 system is up-to-date by issuing the following command:

$ sudo dnf makecache

Next, update your system by entering the command given below:

$ sudo dnf upgrade

After updating your system, install Curl from the standard package repository of CentOS 8 by entering the following command:

$ sudo dnf install curl -y

The “-y” flag will proceed with the installation. When a prompt appears, press “y” to continue the installation process.

After installing curl, issue the following command to verify the installation of Curl:

$ curl

If you obtain an output like that shown in the screenshot above, you have installed Curl successfully, and the program is running perfectly fine. We will now show you how to use Curl on your system.

How to Use Curl on CentOS 8

Let us begin using Curl with a simple URL. If you want to view the source code of any website, simply paste the URL of that website in the terminal, followed by the Curl command. For example, the command for viewing the source code of the LinuxHint website would be as follows:

$ curl https://linuxhint.com

The entire source code of the LinuxHint website will print in the terminal.

Another implementation of the Curl command is to download a file from any URL. For example, to download a file called “index.html” from the URL “www.example.com” using the Curl command, the command would be as follows:

$ curl -O http://www.example.com/index.html

After executing the above command, the “index.html” file will start to download.

Conclusion

This article showed you how to install Curl on CentOS 8 and start using it. This post contains the installation process of Curl, as well as its usage, such as getting the source code of a website and downloading a file from a website. The functionality of the Curl command does not stop here, and it provides a lot of other features to users. You can read the manual page on the official Curl website to learn more.

]]>
How to Install TeamViewer on CentOS 8 https://linuxhint.com/install-teamviewer-centos/ Thu, 25 Feb 2021 00:16:17 +0000 https://linuxhint.com/?p=91449
TeamViewer is a popular multi-platform application that is used for remotely accessing and controlling other desktop systems. TeamViewer is also used for file sharing between two systems. This application is not available in the CentOS 8 package repositories, but it provides the RPM package for installing TeamViewer on RedHat-based operating systems. This article provides a step-by-step guide on installing TeamViewer on CentOS 8 using the RPM file.

Installation of TeamViewer on CentOS 8

Installing TeamViewer on CentOS is pretty simple. Just follow the steps given below to install TeamViewer on your system.

Step 1: Download TeamViewer RPM File

You can download the TeamViewer RPM file from its official website by visiting the following link:

https://www.teamviewer.com/en-us/download/linux/

Click ‘x86-64bit’ to download the 64-bit RPM package for CentOS 8, or select ‘x86_32bit’ on the base of your operating system.

Save the RPM file and press “OK” in the prompt box.

The Teamviewer RPM package will be downloaded in the Downloads folder.

Step 2: Enable EPEL Repository

Fire up your terminal and navigate to the Downloads directory.

$ cd Downloads

Now, before starting the installation process of TeamViewer, we need to enable an EPEL repository on our CentOS 8 machine. First, issue the following command to enable the EPEL repository.

$ sudo dnf install epel-release

Next, update the system’s DNF repository cache.

$ sudo dnf makecache

Step 3: Install TeamViewer Using RPM File

After enabling the EPEL repository, make sure that you are in the Downloads directory. In the Downloads directory, issue the command given below to start the installation process of Teamviewer.

$ sudo dnf install ./teamviewer_15.15.2.x86_64.rpm

Type “y” to give the system permission to take up the required disk space and continue the installation.

The TeamViewer application has now been installed on CentOS 8. After successfully installing the TeamViewer application on CentOS 8, you can launch the TeamViewer application

Step 4: Start TeamViewer Application

To launch the TeamViewer application, go to Activities and search for “TeamViewer.”

From the search results, select the TeamViewer icon by clicking on it to start the TeamViewer application.

Before starting the TeamViewer application, you will be prompted to accept the License Agreement. Accept the License Agreement and proceed to use TeamViewer.

TeamViewer has now successfully started. But, you can see that the application is giving a warning that “Wayland detected” and incoming remote control connections will fail. In the next step, we will fix this warning.

Step 5: Configuring TeamViewer for Incoming Remote Control Connections

Though connecting to other computer systems is possible using TeamViewer, the incoming remote control connections will not be able to access this CentOS machine until you log out from the Wayland session and log in with the X11 display server. To resolve the Wayland detection warning, first, log out from the Wayland session.

Next, click the “Log Out” option,

And, click the “Log Out” button in the prompt, as well.

Then, click the “Settings” icon, as shown in the picture above.

In this menu, you will see options for selecting different display servers. Select the “Standard (X11 display server) on Xorg” option for the modern desktop environment.

After selecting the display server, log in with your CentOS 8 user credentials, and relaunch the TeamViewer application.

Here, you can see that we have successfully configured the TeamViewer application for remote control connections. Now, we can remotely access the designated CentOS 8 machine.

Conclusion

In this post, you learned how to install the latest version of the TeamViewer application on CentOS 8 by downloading the RPM file from its official website. We also showed you how to configure TeamViewer for incoming remote control connections on CentOS 8 by changing the display server from Wayland to X11.

]]>
How to fix “bash: /usr/sbin/ifconfig: No such file or directory” on Linux https://linuxhint.com/fix-ifconfig-command-not-found-linux/ Mon, 22 Feb 2021 16:06:45 +0000 https://linuxhint.com/?p=90286

You were trying to know the IP address of your Linux Operating System, and an error occurred with the message “bash: /usr/sbin/ifconfig: No such file or directory,” and that error has brought you here. Don’t worry; you are reading exactly the right post. But, the question arises that it was working before; what happened?

Why is the “ifconfig” command not working anymore?

The answer is pretty simple; the “ifconfig” command is deprecated in Linux Operating Systems’ upcoming versions. It must be an older version of your Operating System when this command worked for you last time. But, it does not mean you are out of doing anything. You can either know the IP address of your system by typing the command given below.

$ ip a

Or you can install the net-tools on your Operating System if you still want to run the “ifconfig” command.

How to install net-tools on Linux

The net-tools is a toolkit that provides many programs related to Linux networking and allows users to perform network-related tasks. For example,

  • Hostname configuration
  • Netstat tool
  • Address Resolution Protocol Configuration
  • Dig command
  • Ifconfig command

Let’s install the net-tools so that we can run the “ifconfig” command easily. This post will install the net-tools on Ubuntu 20.04 LTS operating System, but the process will be the same for Debian or other Debian-based systems.

Step 1: Update the system’s APT cache repository

First of all, before installing any application in a Linux operation system, it is a better practice to update the system’s APT cache repository first.

$ sudo apt update

After updating the system’s APT repository cache, install net-tools.

Step 2: Install net-tools

The command for installing net-tools on Ubuntu 20.04 is typed below.

$ sudo apt install net-tools -y

The installation of net-tools will start and complete in a couple of minutes.

After the installation of net-tools, you can run the “ifconfig” command.

Step 3: Run the “ifconfig” command

Now, run the “ifconfig” command in the terminal

$ ifconfig

You can see that the network statistics are displayed using the “ifconfig” command.

Conclusion

This post contains a short yet profound and step-by-step guide on installing net-tools to run the “ifconfig” command. This post also provides an alternate “ip a” command to get the network stats without even installing the net-tools. Keep on learning with linuxhint.com.

]]>
How to Download and Install Google Fonts on Ubuntu 20.04 https://linuxhint.com/download-install-google-fonts-ubuntu/ Mon, 22 Feb 2021 09:55:57 +0000 https://linuxhint.com/?p=90272

GoogleFonts offers a huge library of fonts that are free to download and use. You can find the best fonts in the GoogleFonts library and directly download and install them wherever you need from their official website (https://fonts.google.com/). To install any font from Google Fonts in Ubuntu 20.04, you can directly download your desired font from their website and install it in your operating system by double-clicking on the font file.

But, when it comes to installing multiple fonts recursively, practically, it does not seem convenient to download and install every font one by one. Luckily, we have got an application available in the Ubuntu APT package repository named as TypeCatcher.

What is TypeCatcher?

Type catcher is an open-source application developed by Andrew Starr-Bochicchio for installing Google web fonts on any Linux Operating system. This application provides features like

  • Previewing the font style and its size,
  • Searching for font
  • downloading
  • Installing and uninstalling Google Fonts in Ubuntu 20.04

The best part about this application is that it allows users to download and install any font with a single click. The user does not have to install it again manually. So, without any further ado, let’s start.

Installation of TypeCatcher on Ubuntu 20.04

The application is available in the Ubuntu APT package repository and can easily be installed on Ubuntu 20.04 LTS system.

Step 1: Open up Ubuntu’s Terminal

First of all, you have to launch the terminal of Ubuntu 20.04 by using the keyboard shortcut keys (CTRL+ALT+T).

Step 2: Update the system’s APT cache repository

It is a better practice to update your system’s APT package repository before installing any application on Ubuntu. Update the system’s package repository by typing the command given below in the terminal.

$ sudo apt update


After successfully updating the system’s package repository, install TypeCatcher.

Step 3: Install TypeCatcher

To install TypeCatcher on Ubuntu 20.04, type the command given below.

$ sudo apt install typecatcher


Once the TypeCatcher is installed on your system, it will be available in your applications menu.

Step 4: Start the TypeCatcher

You can run and start using Type catcher on Ubuntu by searching for “TypeCatcher” in Ubuntu’s application menu and click on its icon.

You can see that TypeCatcher is installed and running perfectly fine on Ubuntu 20.04.

Step 6: Download and install any Google Font

In this step, we will download and install the “Roboto” font in our Ubuntu system. Before downloading any font, let’s first open up the LibreOffice Writer and search for “Roboto” in the font Name field.

You can witness that it is not installed. Now, let’s install it in our Ubuntu 20.04 system, using the TypeCatcher Application.

In the type catcher application, search for the “Roboto” font in the search bar at the top right corner of the application.

Select the “Roboto” font and click on the Download font icon in the top left corner.

After a couple of seconds, the font will be downloaded, and an installed message will appear in the upper right corner, as shown in the picture below.

Once it is installed, let’s verify that either it is working or not.

Step 7: Verify the Font’s installation

Switch to the LibreOffice Writer and again search for the “Roboto” font.

You can see that now we got the “Roboto” font listed in the font name field of LibreOffice Writer. This is just a kind of proof that the “Roboto” font is successfully installed and working perfectly fine in the Ubuntu 20.04 LTS system.

Conclusion

This post contains the step-by-step guide on installing the TypeCatcher application on Ubuntu 20.04 and how to download and install the Google Fonts using the TypeCatcher Application on Ubuntu 20.04.

]]>
How to reset the root password on Ubuntu 20.04 if forgotten? https://linuxhint.com/reset-root-password-on-ubuntu-20-04/ Fri, 19 Feb 2021 03:18:33 +0000 https://linuxhint.com/?p=90195
You have forgotten your root password, and now you have no idea how to retrieve your Ubuntu 20.04 LTS Operating System? In this post, we will guide you on how to reset your root password on Ubuntu 20.04 LTS System from the GRUB menu. The Grand Unified Bootloader or GNU GRUB menu is a boot loader and software or program that loads and transfers control to the Operating System like Linux-  it runs when a computer starts. So, let’s begin with the step-by-step guide of resetting the password of the root.

Step 1: Reboot your Ubuntu 20.04 LTS Operating System and load the GRUB menu by holding the Shift Key on Keyboard

The first step is to start your computer machine and keep pressing the shift button on your keyboard until the GRUB menu appears, as shown in the picture below:

Step 2: Press ‘e’ to edit the commands

Now, select the boot Operating system, which is Ubuntu in our case, and press the ‘e’ key on your keyboard to edit some commands. By doing so, we can load the root shell Command prompt. Pressing the ‘e’ key on your keyboard allows you to have an edit screen, as shown in the picture below:

Step 3: Edit the clause of the second last line from ‘ro quiet splash $vt_handoff’ to ‘rw init=/bin/bash’

After entering into the editing mode of commands, scroll down until the last, find a line that starts with the word ‘linux’ and change the last clause of this line that reads ‘ro quiet splash $vt_handoff’ to this clause, ‘rw init=/bin/bash’, as shown in the pictures below:

Before

ro quiet splash $vt_handoff

After

rw init=/bin/bash

Step 4: Press F10 or Ctrl-x to save the edits and boot

Once you have edited the line for loading the root shell command prompt, Press F10 or CTRL+X to save and boot the system. After the reboot, a shell command prompt screen of the root will appear, as shown in the picture below:

Step 5: Type the command ‘mount | grep -w /’ to confirm the read and write access rights

In the root shell command prompt screen, type the command given below for confirmation of the read and write privileges.

# mount | grep -w /

Step 6: Type the ‘passwd’ command and provide the new password for the root

Once read and write access rights are confirmed, type the ‘passwd’ command and enter or set the new password for the root.

# passwd

You can see that the password is updated successfully.

Step 7: Type the command ‘exec /sbin/init’ to reboot your Ubuntu 20.04 LTS Operating System

After successfully updating the password of the root, the last step is to just reboot your system by typing the command given below:

# exec /sbin/init

After running the above command, your computer will reboot and load the welcome screen of the Ubuntu 20.04 LTS system.

Conclusion

The article contains a step-by-step and easy-to-understand guide on how to reset your forgotten root password on the Ubuntu 20.04 LTS system.

]]>
Set up LAMP(Linux, Apache, MySQL, PHP) Stack on Ubuntu 20.04 https://linuxhint.com/install-lamp-stack-ubuntu/ Thu, 28 Jan 2021 15:45:37 +0000 https://linuxhint.com/?p=87968

You might have just started building your dynamic web application in PHP, and you want to set up the LAMP Stack. LAMP term comes from the Linux Operating System, Apache server, MySQL database, and PHP language. Let’s get started with the installation of LAMP Stack on Ubuntu 20.04.

First of all, you should have sudo privileges on your system or log in as a root to perform the following tasks:

Update the System’s Package Repository

To get started with all the installation, it is the best practice to update the APT cache repository first so that all the latest applications can be installed smoothly.

$ sudo apt update


Once the apt-cache is updated, we are ready to move forward with the LAMP Stack installation.

Let’s first install MySQL.

Install MySQL on Ubuntu 20.04

Since MySQL is mostly used as a database with PHP and used to manage and store data to install MySQL on your ubuntu system, type the command given below.

$ sudo apt install mysql-server mysql-client


It will ask you to take additional disk space for the package to install, so press “y” to continue installing MySQL.


Once MySQL is installed, check the version by typing this command.

$ mysql --version


And to check that MySQL’s service is running or not on your ubuntu system, type this command to check the status.

$ sudo systemctl status mysql.service


If it is not active, you can start it by using the start keyword in the above command like this

$ sudo systemctl start mysql.service


To login to the MySQL’s shell, type the following command

$ sudo mysql


It won’t ask you for any password for the first time.

Once you log in to MySQL’s shell, you can set up your password or perform any function related to the database in it.

Now let’s exit through it and install the Apache 2 web server on the Ubuntu system.

mysql> exit

Install Apache Web Server on Ubuntu 20.04

Apache 2 is a web server that handles the servers for hosting web applications. To install Apache 2 on your ubuntu system, run this command.

$ sudo apt install apache2


It may also prompt for taking a grant of additional disk space for the Apache’s installation, so press “y” to continue the installation process.

Once, Apache 2 web server is installed as well; you can check the status by typing the following command.

$ sudo systemctl status apache2


If it is active and running, then you are good to go with the installation of PHP; otherwise, start using the command

$ sudo systemctl start apache2


After starting it, let’s install the PHP now,

Install PHP on Ubuntu 20.04

PHP’s latest stable version can easily be installed on ubuntu from the APT package repository by typing the command given below in the terminal

$ sudo apt install php


Press “y” to continue the process if it prompts for taking additional disk space for installing PHP.

After the successful installation of PHP, you can check the version by typing the command

 $ php --version


PHP version 7.3.4 is installed.

Install PHP Extensions

Now if you want to install some other basic PHP extension as well, which are required for the phpMyAdmin, For example,

  • php-curl
  • php-gd
  • php-mbstring
  • php-mysql
  • php-zip
  • php-json
  • php-xml

You can do so by typing the following command.

$ sudo apt install php-curl php-gd php-mbstring php-mysql php-zip php-json php-xml


Allow it to take additional disk space for the extensions to install by typing “y” and hitting the “Enter” button.


This command will install all the required PHP extensions for running the phpMyAdmin.

So this is how you can install all the required packages on Ubuntu 20.04 and set up the LAMP Stack for building your dynamic web application.

Conclusion

This post contains the step by step guide to install and set up the LAMP stack on Ubuntu 20.04 LTS.

]]>
MySQL Primary and Foreign Keys https://linuxhint.com/mysql-primary-and-foreign-keys/ Mon, 28 Dec 2020 08:11:55 +0000 https://linuxhint.com/?p=83392

MySQL is an RDBMS (Relational Database Management System) which is owned by the Oracle Corporation and inherited from the standard SQL. It allows access and manipulation of Databases. Whoever knows the word ‘Database’  must have knowledge of Primary and Foreign keys. There is no concept of a relational database without the existence and idea of the concepts of Primary Keys and Foreign Keys. So in this article, we are going to learn about the importance and correct use of Primary and Foreign keys in MySQL.

The primary key can be any field or column of a table, which should be a unique and non-null value for each record or a row.

The Foreign key is a field that contains the primary key of some other table to establish a connection between each other.

Let’s have a look at the syntax and different examples to create primary and foreign keys in MySQL.

Primary Keys

We can make a primary key on a segment of the table by utilizing the ALTER TABLE.

Primary key while creating a table

Suppose that we want to create a table of books in MySQL that contains the ID, name, and category of a book, in which the ID column will be the primary key.

The query for creating such a table and creating the ID column a primary key column will be like this:

CREATE TABLE books (
book_id INT NOT NULL,
book_name VARCHAR(255) NOT NULL,
book_category VARCHAR(255),
PRIMARY KEY (book_id)
);

In this syntax, we can define constraints at the end of the query.

If we describe the table,

DESC books;

We can see in the column of the key that the book_id is set as the Primary Key of the table.

Drop a Primary key

Instead of adding, if we want to delete or drop a primary key, the ALTER command is used.

So, this is all about how we can create and delete a primary key in a table.

Primary key creation via ALTER TABLE

To define a primary key, we can put the ALTER TABLE into use.

ALTER TABLE books
ADD PRIMARY KEY (book_id);

The primary key is added successfully. Now, let’s learn about the foreign keys a well.

Foreign Keys

Just like primary keys, foreign keys can be defined while defining the table using the ALTER TABLE command.

Foreign key while creating a table

In the primary key section, we have created a table for the books. Now, let’s suppose, we have another table of authors in our database that includes the author’s ID as a primary key, author’s first name, and last name,

DESC authors;

And we want to create a foreign key to the author’s ID in the books table. So, to create a foreign key on author_id while creating the books table, we run this query:

CREATE TABLE books (
book_id INT NOT NULL,
book_name VARCHAR(255) NOT NULL,
book_category VARCHAR(255),
author_id INT,
PRIMARY KEY (book_id),
FOREIGN KEY (author_id) REFERENCES authors(author_id)
);

Drop a Foreign key

Dropping a foreign is not the same as dropping a primary key. We first have to get the name of the constraints by running the “SHOW CREATE TABLE books” command.

Then provide the constraint name to the ALTER TABLE command like this:

ALTER TABLE books
DROP FOREIGN KEY books_ibfk_1;

This is how we can create and delete a foreign key in a table.

Primary key using the ALTER TABLE command

For creating a foreign key on an existing table using the ALTER TABLE command,

ALTER TABLE books
ADD FOREIGN KEY (author_id) REFERENCES authors(author_id);

Let’s DESC the books table:

DESC books;

We can see that the author_id is set as the foreign key successfully.

Summary

We have learned about the profound and concepts of Primary keys and Foreign keys. As well as the creation, addition, and deletion of a primary or foreign key in a table.

]]>
MySQL Outer Join https://linuxhint.com/mysql-outer-join/ Mon, 28 Dec 2020 07:47:34 +0000 https://linuxhint.com/?p=83379

MySQL provides a lot of commands, which are needed while managing a database. For example, we often need to get some data from different tables based on some condition. MySQL then provides different types of joins to get the desired results. Let’s learn LEFT JOIN AND RIGHT JOIN of MySQL.

There is no such statement as FULL OUTER JOIN in SQL, but we can use a simple JOIN to get the same results or by simply using a SELECT statement over two different tables.

Otherwise, MySQL provides LEFT JOIN and RIGHT JOIN to get the records or rows from the right or left table, respectively. Let’s try a couple of different examples to get the desired results using appropriate joins.

Examples

Before we start learning the usage of LEFT and RIGHT JOIN. We will learn how to get all of the data from both of the tables (either common or uncommon) using the simple SELECT statement and using the CROSS JOIN with the SELECT statement. First, let’s try to get all of the data from both of the tables using the SELECT statement.

For instance, there are 2 tables that we got by the name of the author and books.

DESC books;

DESC authors;

If we want to get all the columns from both of the tables. The SELECT query will be used like this:

SELECT * FROM books, authors;

As you can see, we have all the columns from both of the tables without even providing a condition.

If we use the JOIN or CROSS JOIN clause, both will bring us the same results. For example:

SELECT * FROM books JOIN authors;

Now, let’s try to apply the CROSS JOIN:

SELECT * FROM books CROSS JOIN authors;

As you can witness, all of these queries are bringing us the same results.

However, it is not good to have all the columns in such an abstract form. So, to get a few specific columns from the left or right table, there are two ways in which you could proceed; one way is that you use column names using SELECT statements or using joins that fit your requirement.

Alright, now let’s move forward to understand the LEFT JOIN and RIGHT JOIN.

LEFT JOIN

Suppose that we want to get some specific columns that are either from the books table or common between the books and authors table, based on some condition, the condition is actually provided by comparing two different tables. For example, we want to join two tables, books, and authors where the book’s ID is equal to the author’s ID. We can expect such a result by using LEFT Join with SELECT statement; SELECT query with the column names that you want to get from either the books table or authors. The SELECT query with the LEFT JOIN and condition would be like this:

SELECT books.book_name, books.book_id, authors.author_id,
authors.author_fname, authors.author_lname
FROM books
LEFT JOIN authors
ON books.book_id = authors.author_id;

Since we have mentioned the books table on the left side, the join will get the ID of one row from the books table and look for the same ID number in the author’s table. If it finds the same ID number, it will also show the given columns from the author’s table. Otherwise, it will show NULL in the columns of the author’s table. Let’s execute this query and witness the results.

As you can see, we have the rows from both of the tables where the books table ID is equal to the author’s table ID. In the last row, we can also see that there is no ID number 4 in the author’s table, so it has returned NULL against it.

RIGHT JOIN

Similarly, if we want to get some data, either from the author’s table or common between the books and the author’s table, based on some conditions, this kind of results can be expected by using the RIGHT join and SELECT clause. The SELECT query with the RIGHT JOIN and condition would be like this:

SELECT books.book_name, books.book_id, authors.author_id,
authors.author_fname, authors.author_lname
FROM books
RIGHT JOIN authors
ON books.book_id = authors.author_id;

This time, we know that the authors’ table is on the right side, so the join will get the ID of one row from the author’s table and look for the same ID number in the book’s table. If it finds the same ID number, it will show the given columns from the books table. Executing the query would result in this:

As you can see, we have the rows from both of the tables where the author’s ID is equal to the book’s ID. We know that there was a fourth book in the books table, although we didn’t get it, this is because of the RIGHT JOIN.

So, this is how the LEFT JOIN and RIGHT JOIN truly works.

Conclusion

We have learned and understood the CROSS, LEFT, and RIGHT JOIN, as well as learned to use them to get the desired results in MySQL. We also have tried a couple of different examples of JOINS to understand the concepts in a better and profound way. So keep visiting our website linuxhint.com for more useful content like this.

]]>
Insert Data Into a Table in MySQL https://linuxhint.com/insert-data-into-a-table-in-mysql/ Sat, 26 Dec 2020 08:02:15 +0000 https://linuxhint.com/?p=82752

With MySQL we can perform all the CRUD operations and some other major commands that are necessary for building an interactive application. Data insertion is one of the most used operations in any DBMS (Database Management System). So, in this article, we are going to learn some of the different ways to insert data into a table using the INSERT statement in MySQL.

INSERT statement is used to insert data in rows of a table.

Syntax

The syntax for inserting data into a table is:

INSERT INTO table_name (column_name_1, column_name_2, ...)
VALUES (value_1, value_2, ...),
(value_1, value_2, ...),
...
(value_n1, value_n2, ...);

In this syntax:

First, mention the table_name (in which you want to insert data) along with the column names in parentheses (column_name_1, column_name_2, …) (columns of the table), followed by the INSERT INTO clause.

After mentioning the table name and column names in parentheses, you need to provide the values after the VALUES clause like this:

(value_1, value_2, …); these are values or data you want to insert corresponding to the columns.

You can also provide or add multiple rows in a single query by separating them with a comma.

Let’s try some examples of data insertion into a table in MySQL and have a better understanding of the INSERT command.

Examples

Before getting started learning the data insertion. Let’s first create a table and set some different data types of the columns so that we can insert different types of data. The query for creating a table would be like this:

CREATE TABLE IF NOT EXISTS cars (
car_id INT AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
manufacturing_date DATE,
engine VARCHAR(25) NOT NULL DEFAULT 'Gasoline',
description TEXT,
PRIMARY KEY (car_id)
);

In this query, we have created a table with the name of cars, which includes the following columns:

An integer type car_id column with the constraint of AUTO_INCREMENT (which means that during data insertion, even if we don’t provide any value, it will automatically increment the value and add that value in this column).

A name column with the data type of VARCHAR, which includes the name of the car, and set the constraint so it can’t be NULL.

A manufacturing_date column will have the date of when the car was manufactured.

An engine column will have the engine type. For example, Gasoline, Diesel, or Hybrid. We have set the constraints that forbid this value to be null, and if it is not provided while inserting a new row, then it sets the default value to  ‘Gasoline’.

A description column that includes the description of the car.

And in the end, we have created a primary key on the car_id column.

After creating a table successfully, let’s move towards the data Insertion.

INSERT Command

In the INSERT command, it is not necessary to insert data into all the columns. We can just insert data into some specific columns until we are fulfilling the requirements that we have during the creation of the table. So, let’s first try to enter the car name and its engine type only. The query for inserting the data would be like this:

INSERT INTO cars (car_name, engine_type)
VALUES ('HONDA e', 'Electric');

After successfully adding one row to the table. The table should be updated.

SELECT * FROM cars;

As you can see, we have not added any car_id, but because of the AUTO INCREMENT constraint, the car_id is automatically inserted, along with the other two fields

Well, we can also provide the DEFAULT keyword while inserting data. When we provide the DEFAULT keyword while inserting data, the DEFAULT value that will be assigned is what we have set during the creation of the table. For example:

INSERT INTO cars (name, engine)
VALUES ( 'FERRARI F8', DEFAULT);

Now, let’s take a look at the table again.

SELECT * FROM cars;

The default value ‘Gasoline’ is assigned. That’s great!

Alright, now, let’s learn about the format of inserting the date into MySQL’s Table.

Insert Date into a table

To insert a date into MySQL, we need to follow the following syntax:

‘YYYY-MM-DD’

Year, Month, and Date are separated by dashes. For Example:

INSERT INTO cars (name, manufacturing_date, engine)
VALUES ( 'BMW M5', 2020-09-15, DEFAULT);

Or if you want to insert the current date. We can use MySQL’s built-in functions like CURRENT_DATE() or NOW(). You can get today’s date by using any of these functions. For example:

INSERT INTO cars (name, manufacturing_date, engine)
VALUES ( 'BMW I8', CURRENT_DATE(), 'Hybrid');

Similarly, the NOW() function would do the same for us:

INSERT INTO cars (name, manufacturing_date, engine)
VALUES ( 'BMW X6', NOW(), 'Diesel, Gasoline, Hybrid');

Now, let’s see the current status of the table.

SELECT * FROM cars;

It can be observed that today’s date is inserted successfully by both of the functions.

Alright, now, let’s try to insert more than one row in a single INSERT statement.

Inserting Multiple Values

To insert multiple values, we can provide them in the parentheses separated by a comma followed by the VALUES clause. For example:

INSERT INTO cars (name, manufacturing_date, engine)
VALUES ('AUDI A3 Sedan', CURRENT_DATE(), 'Gasoline, Diesel'),
('AUDI Q7', '2020-06-11', 'Gasoline, Hybrid, Diesel, Electric'),
('AUDI S8', NOW(), DEFAULT);

In this single query, we have added three different car models of AUDI in three different rows of the ‘cars’ table. The table should contain three added rows.

As you can see, all of the three rows are inserted as we desired.

So, these are some of the different syntaxes and ways to insert data into a table.

Wrapping Up

In this article, we have learned different syntaxes to insert different types of data into the table. We have also learned to use the CURRENT_DATE() function, NOW() function, and DEFAULT keyword to understand the different syntaxes for adding or inserting data into a table.

]]>
Delete or Drop a User in MySQL https://linuxhint.com/delete-drop-a-user-in-mysql/ Mon, 14 Dec 2020 08:55:18 +0000 https://linuxhint.com/?p=81655

MySQL is a well-known database that can be used with ease and no hassle and is used in a lot of big firms. Data integrity and Data administrators mean a lot to such huge companies. But when it comes to data integrity and taking care of the users, their privileges, and the creation and deletion of them, the database administrator takes responsibility for such tasks. So, in this article, we are going to learn about different methods to delete or drop a user in MySQL.

Before we get started learning about the user’s deletion in MySQL, it is assumed that you know how to create and list the users and have already installed MySQL on your system. So, figure out the version of MySQL using the command below:

mysql -V

If you could see the version, it means that it’s already installed. Moving forward, we will figure out the status of the system’s mysql.service. Then, we would be able to sign in to the MySQL server.

sudo systemctl status mysql

In case the service hasn’t started, you can initiate it with the following command:

sudo systemctl start mysql

Once the service begins, you can connect yourself to the MySQL shell as a root user so, you can pretty much access everything inside.

sudo mysql -u root -p

After logging into MySQL, list the user names and hostnames from mysql.user by running the following command:

SELECT user, host FROM mysql.user;

After having a look at the list of users, select the user you want to drop/delete.

There are two ways to delete a user with a subtle difference. If you want to delete an already existing user and you know its name, you can run the simple “DROP USER” command, along with the user name and its hostname. Like this:

DROP USER 'user_name'@'host_name';

But if you do not know or remember the name of the user and have a hunch of the user’s name, then MySQL provides the IF EXISTS clause to help in such scenarios. If the user’s name exists in the MySQL against the provided name in the query, it will get deleted for sure. Otherwise, it won’t get deleted. However, if we do not utilize the IF EXISTS clause, MySQL won’t work, and you would see an error. So, it is recommended to use the IF EXISTS clause if you are not sure about the existence of the user’s name in MySQL. The general syntax if you want to use the IF EXISTS clause is shared below:

DROP USER IF EXISTS 'user_name'@'host_name';

You can delete or drop multiple users in a single query as well by running the following command in MySQL’s shell:

DROP USER 'user_name1'@'host_name1' 'user_name2'@'host_name2';

When you have deleted the user, you can check the list of users again, whether the user still existed in the list or not.

SELECT user, host FROM mysql.user;

You can see in the list that the deleted user or users are not there anymore.

So, this is how we can delete or drop a user in MySQL using the DROP command.

Conclusion

In this article, we have learned two different syntaxes for deleting the user in MySQL. We have also learned to delete multiple users in a single query as well.

]]>
Vue.js vs. Django https://linuxhint.com/vue_js_vs_django/ Mon, 14 Dec 2020 06:35:36 +0000 https://linuxhint.com/?p=81446

When you are required to choose a library or framework for building web applications, there is no question that JavaScript libraries are preferred over any other library. But that does not mean that other libraries are not good enough.

Vue.js and Django are both famous JavaScript web frameworks. They are also both open-source tools. Vue.js is famous for building clean, reusable, component-based web applications. Django is a framework that is built on Python and is known for its rapid development and rational code design.

In this article, we will discover some of the basic and more technical differences between Vue.js and Django. This includes the pros and cons of each framework, the companies that currently use these frameworks, integrated tools, and much more.

Difference between Vue.js and Django

Vue.js is a front-end JavaScript framework that generates pages on the client-side. Because it renders pages on the client-side, Vue.js costs more initial load time, but it gives a better experience when it is necessary to navigate between pages.

While Django is a full-stack Python framework and it generates pages on the server-side. Its server-side rendering helps in initially loading the page but while navigating we may have to face performance issues due to the network latency.

Pros of Vue.js

Vue.js is a simple, easy-to-use, and fantastic library for your needs. You can learn it hands-on if you know Html, CSS, and JavaScript. Vue.js is a framework with a fast learning curve signature. The documentation written for Vue.js is also easy to understand and extremely detailed, as well.

The documentation is so well written that you should not feel confused, even when working with it all day. All steps are explained clearly and the Vue.js documentation is one of the best guides available for any web framework. Vue.js is a complete and functional JavaScript ecosystem, and it stands as one of the top front-end frameworks.

Pros of Django

Django is known for its rapid development, and it is an open-source tool. This framework has a great community, as well. Django is an elegant MVC Framework that helps you in writing beautiful code. This framework is free to use, has great documentation, and is very easy to learn, as well. It also provides great packages and libraries to help in development.

Cons of Vue.js

The community of Vue.js is smaller than the other two competitive frameworks, reactJS and Angular. Vue.js does not support fragments, and it only supports multiple root nodes programmatically. Another con of Vue.js is its YXML vs. HTML markup.

Cons of Django

Django is an underpowered templating framework and has an underpowered ORM. Its auto-reload restarts the whole server. Django’s URL dispatcher ignores the HTTP method and has some coupling of internal subcomponents.

Having cons does not necessarily mean that a framework is bad. Actually, every framework comes with the intention of fulfilling some particular need or providing some specific value. It is a well-known fact that every framework has its own features and standards that differentiate it from other frameworks, and it is easy to prioritize one over another according to your needs.

Companies that Use Frameworks

Both of these frameworks are backed by good companies.

Vue.js is backed by a lot of big names, such as:

  • Alibaba
  • Xiaomi
  • Laracast
  • Trivago.com

Django is also backed by some big names, such as:

  • Pinterest
  • Instagram
  • Udemy
  • Robinhood

Conclusion

In this article, we reviewed both the Vue.js and Django frameworks and pointed out their differences. We also discussed the pros and cons of each framework and mentioned the name of the companies backed by these frameworks. Vue.js is becoming quite popular among JavaScript frameworks and front-end web development at an increasing pace, specifically in terms of single-page applications and user interfaces. Meanwhile, Django will have its own recognition of being a full-stack and rapid development framework.

]]>
MySQL Inner Join https://linuxhint.com/mysql_inner_join/ Mon, 14 Dec 2020 06:04:57 +0000 https://linuxhint.com/?p=81451

MySQL is a well-known database derived from standard SQL. It is one of the most popular databases out there. MySQL allows you to perform CRUD operations and all other major commands needed when managing a database. When you need data from different tables based on specific conditions, MySQL provides joins to handle these types of tasks. This article covers the MySQL inner join in detail.

What is an inner join? An inner join is the same as a simple join. An inner join returns common records or rows from the provided condition(s) and tables. We can use any of these clauses and we will still have the same results. Let us look at some examples to show you how to correctly use inner joins in MySQL.

Examples

Before learning the usage of inner joins, We can get the result from two different tables based on the condition(s) by using the SELECT statement and the WHERE clause. In the following example, ‘books’ and ‘authors’ are two different tables in a database.

DESC books;
DESC authors;

In the ‘books’ table, we have the foreign author_id key from the ‘authors’ table.

To get all the columns from both tables, we set books.author_id = authors.author_id. The SELECT query would be as follows:

SELECT * FROM books, authors

WHERE books.author_id = authors.author_id;

As you can see in the image above, we have obtained all columns from both tables. Often, it does not look good to have all the columns, even if they are not needed. So, if you want to obtain only certain columns from both tables, you will need to mention the column names in the SELECT statement, as follows:

SELECT books.book_name, books.category, authors.author_fname, authors.author_lname

FROM books, authors

WHERE books.author_id = authors.author_id;

As you can see, we have a clean and clear-cut output of the four provided columns from both tables.

Now, we will perform the same task using the INNER JOIN clause.

To join two tables using the INNER JOIN clause, the SELECT query would be as follows:

SELECT books.book_name, books.category, authors.author_fname, authors.author_lname

FROM books INNER JOIN authors

ON books.author_id = authors.author_id;

As you can see in the screenshot above, we have obtained the same output, but using the INNER JOIN clause this time.

As stated earlier, the INNER JOIN clause is the same as a simple JOIN clause. This means that we can use the JOIN clause instead of the INNER JOIN clause and still obtain the same results. The SELECT query with the simple JOIN clause would be as follows:

SELECT books.book_name, books.category, authors.author_fname, authors.author_lname

FROM books JOIN authors

ON books.author_id = authors.author_id;

As you can see in the image above, we have obtained the same results. This shows you that the simple JOIN and INNER JOIN clauses are the same. You can get the same results using any of these join clauses.

The concept of the inner join does not stop here. In previous examples, we applied the join on two tables on the basis of the author_id key. Since we know that the author_id key is already the foreign key in the ‘books’ table, we may shorten the syntax by using the USING clause with the join. The syntax for using the USING clause with the JOIN clause is as follows:

SELECT books.book_name, books.category, authors.author_fname, authors.author_lname

FROM books JOIN authors

USING (author_id);

It can be observed that this query has generated the same results with the USING clause.

Similarly, we can apply a condition along with applying the join between two tables using the WHERE clause. For example, to get the same four columns from both tables  in which the author’s last name is equal to ‘Hill,’ the query for getting such output will be:

SELECT books.book_name, books.category, authors.author_fname, authors.author_lname

FROM books JOIN authors

USING (author_id)

WHERE authors.author_lname = 'Hill';

As you can see in the image above, we only obtained two rows in which the last name of the author is ‘Hill.’

So, now, you have seen some examples of the different ways to use an inner join to get the results you want in MySQL.

Conclusion

In this article, we tried a couple of different examples of using the inner join to provide a more complete understanding of the concept. You also learned how to use the USING and WHERE clauses with the inner join, as well as how to obtain the required results in MySQL. For more useful content like this, keep visiting our website, linuxhint.com.

]]>
MySQL Update Statement https://linuxhint.com/mysql-update-statement/ Sat, 12 Dec 2020 08:28:40 +0000 https://linuxhint.com/?p=81048

MySQL is an open-source Database Management system, which can be used for both small and large projects. Developed by The Oracle Corporation, it uses standard SQL behind it. In database management, CRUD operations are a kind of basic requirement to know.

In this article, we will learn to update the data in MySQL tables using MySQL’s provided UPDATE statement. An UPDATE statement is basically a DML (Data Manipulation Language) statement because it modifies or updates the data.

Syntax

The syntax for updating a column or columns in a table in MySQL is:

UPDATE table_name
SET
column_name = value,
...
[WHERE condition]

In this syntax, table_name is the table in which you are willing to update any column.

By using the SET clause, we can assign new values to multiple columns by using the equal sign “=”.

column_name is that column where you want to make an update.

In the end, we can also provide the WHERE clause to apply some condition or filter the updating process.

Let’s make it clear by showing an example in which we would update the value of a column inside a table.

Example

First, open up your terminal and log in to the MySQL shell and choose the database in which you want to update a table. In order to see all the tables inside a database, run this command:

We have one table in our selected database. Let’s see whether some data exist in it or not. To see the data in a table, run the SELECT command as follows:

SELECT * FROM cars;

Suppose we want to update the car’s name and manufacturing date of the third row from “BMW I8” to “BMW M4” where car_id is 3, Then the query for updating the name and date would be like this:

UPDATE table_name
SET
car_name = ‘BMW M4’,
man_date =2020-10-10
WHERE car_id = 3;

After running the update command and having an output of “1 row(s) affected”, now, let’s view the table:

SELECT * FROM cars WHERE car_id = 3;

As you can see in the screenshot given below, the data of the third row is updated successfully.

So, this is how you can update the data of any table in MySQL using the UPDATE statement.

Conclusion

We have come to know the utilization of UPDATE statement and how we can update data in any MySQL database. Then, we have discussed how to update a single column, as well as multiple columns at once. Lastly, we have also seen the use of the WHERE clause.

]]>
List or Show Tables in MySQL https://linuxhint.com/list-show-tables-in-mysql/ Sat, 12 Dec 2020 08:18:26 +0000 https://linuxhint.com/?p=81044

MySQL is one of the most famous open-source and freely available DBMS (Database Management Software System). It has an easy-to-use interface and is famous for its speed. If you are doing a job as a database administrator in some big organization, you often need to go through a large number of databases and their tables. So, in this article, we are going to learn how we can list or show tables in the MySQL shell.

In order to get started with listing and showing the tables in a database, login to MySQL shell as a root user by running the following command in the terminal:

sudo mysql -u root -p

Then, select the database by running the USE statement of MySQL:

USE database_name;

If you don’t know what databases you have, you can list the databases by running the SHOW DATABASES command of MySQL:

After selecting a database, the simplest and easiest way to list tables is to run the SHOW TABLES statement of MySQL in the shell:

You can see the list of tables in the selected database in the screenshot below.

However, this list only contains the name of the tables. MySQL provides another statement to show the type of the table. Either it is a view or a base table. We can see the table type as well by adding the FULL clause in the SHOW TABLES statement:

As you can see in the screenshot below, we have got the table type as well in the second column, along with the table names.

In MySQL, we can actually list or show tables without selecting a database first. As we did earlier, we do not need to select a database first before listing the tables. We can get the list of tables of any database by running the following command:

SHOW TABLES FROM database_name;

Or if you have a long list of tables and you want to filter through them. You can also use the LIKE clause to do so:

SHOW TABLES LIKE pattern;

To understand the pattern. Suppose we want to list all the tables whose name starts from the ‘tes’. The command for showing the tables will be like this:

SHOW TABLES LIKE 'tes%';

The percentage ‘%’ sign denotes that there can be any or no character after that.

Just like how we listed tables without selecting the database first. We can list the tables from a specific database without logging into the MySQL shell as well. In order to accomplish this, run the following command in the terminal:

sudo mysql -u user_name -p -e 'SHOW TABLES FROM database_name'

The ‘-e’ is for executing the MySQL statement.

As you can see in the screenshot, we got the same output or list of tables in the terminal without logging into the MySQL shell and selecting the database.

So, these are some of the ways to show the tables and filter them.

Conclusion

In this article, we have learned how to show the tables in a database in MySQL using different methods. We have also learned how to filter the list of tables using the LIKE clause.

]]>
List Users in MySQL https://linuxhint.com/list_users_in_mysql/ Tue, 08 Dec 2020 12:50:43 +0000 https://linuxhint.com/?p=79666

MySQL is the most widely used, free open-source DBMS (Database Management System). It is used by some of the famous organizations like NASA, US NAVY, Tesla, Twitter, Spotify, and a lot more. If your work is related to database administration tasks for huge organizations and corporations, responsible for data integrity, and care for the privileges that users have over too many databases, then this article is for you. It will guide you in listing the users, look at the privileges they have, and list the users on behalf of a database. This is because we can list the users using MySQL’s own built mysql.user table.

To list down the users in MySQL, we first need to login to the MySQL server.

We can log in to the MySQL server as a root user by running the following command:

sudo mysql -u root -p

If you are unable to login, there is a possibility that your system’s mysql.service is not active and running. So, to start the service, run the following command:

sudo systemctl start mysql

To check the status of the service, use the following command:

sudo systemctl status mysql

If it is active and running, try to log in now.

After logging in to the MySQL server, we can list all the users regardless of the access they have over the different databases by using the SELECT statement and MySQL’s build mysql.user table.

SELECT * FROM mysql.user;

As you can see in the screenshot, we got a lot of information. MySQL has a table for the list of users. So, if we want to trim down the columns to have a few columns instead of using an asterisk, MySQL provides the DESC statement to get all the column names and fields of the user’s table.

To get the user’s table run the following command:

DESC mysql.user;

After having a look at the table, we can list a limited amount of information and have a few columns about the user. Instead of using an asterisk sign in the SELECT statement, we can provide the column names and list the users by running the  command in the example below:

SELECT user, host FROM mysql.user;

As you can see in the screenshot attached, we have a list of only two columns now.

Conclusion

This article contains a very basic and easy to follow concept to list the users in MySQL using different techniques. We have learned how we can use the column names of myqsl.user to trim the list and have a better insight.

So, for more useful content and a better understanding of database concepts, keep visiting linuxhint.com.

]]>
Delete/Drop a Table in MySQL https://linuxhint.com/delete-drop-table-mysql/ Tue, 08 Dec 2020 11:30:51 +0000 https://linuxhint.com/?p=80161

MySQL is a relational database management system that provides quick and reliable solutions. It is well-known for its ability to execute quickly and for its unique and straightforward user experience. Performing CRUD operations are the core operations and basic concepts when working with databases. In this article, you will learn how to delete a table in a database.

Before learning more about the deletion of tables using MySQL, be sure that you have the latest version of MySQL installed on your computer. Also, ensure that you have a database and a table in it that you want to delete. In this article, we assume that you understand the basic concepts of MySQL statements and that you have a database and table in MySQL that you would like to delete.

You can figure out the version of MySQL running on your system by running the ‘mysql -V’ command:

mysql -V

You can now move forward knowing that you have the latest version installed.

To figure out whether MySQL is working properly, run the following command:

sudo systemctl status mysql

If the service is not running, then you can activate the service using the command below:

sudo systemctl start mysql

After starting it, connect to the MySQL server as a root user with superuser privileges using sudo. Otherwise, you can enter a custom username instead of the root username.

The following steps show the table deletion process for MySQL servers in the command-line terminal.

sudo mysql -u root -p

After entering the MySQL shell, list the databases and choose the database from which you want to delete a table.

Select the correct database by running the USE statement with the database name.

USE database_name;

After choosing the database from the list, choose the table, as well. To see a list of the tables in the database, run the SHOW TABLES command:

Now, choose the table that you would like to delete. To delete the table, run the “DROP TABLE” command and provide a table name, for example:

DROP TABLE table_name;

If you are unable to delete or drop a table, make sure that you have the correct privileges for that table. If you do not have the privileges issue but are still getting an error when attempting to delete a table, then you may be trying to delete a nonexistent table, or there could be a spelling mistake. To avoid this error, MySQL provides the “IF EXISTS” clause. If you use this clause, MySQL will not throw any errors if no table exists of the given name in the query in the database. The “IF EXISTS” clause has a specific syntax that needs to be followed, shown below:

DROP DATABASE IF EXISTS database_name;

Conclusion

This article includes two different methods of deleting an existing table in a MySQL database, both with and without using the “IF EXISTS” clause. The article also described the difference between these two methods for your convenience.

]]>