Categories
Tutorials WordPress

How to install WP CLI in Windows

What is WP CLI?

As part of my experience working on WordPress since 2009, which counts as more than 14 years, one of the working tools I would recommend to new WordPress developers is WP CLI.

So what is WP CLI? It’s a command line interface that allows developer to manage their WordPress sites using command prompt, if you are using Windows or Terminal if you are using Linux.

One of the commands that is useful(to me at least) is when I clean up thousands of spam comments without using bulk action, which is limited to 25 posts deletion per request. Not to mention that would be time-consuming. A single WP CLI command will do this once in under 1-3 seconds.

$ wp comment delete $(wp comment list --status=spam --format=ids)

How to install WP CLI?

While I recommend developers use Linux-based operating systems for their workstations, some of us still find Windows as our main operating system. This tutorial will walk you through installing WP CLI on Windows.

The first thing I would recommend is that we avoid using Windows default command prompt and instead use git-scm. Download and install https://git-scm.com/download/win first. We will use this command interface for the rest of our work.

Second, we need to install Composer. Download Composer-Setup.exe which will give you the latest Composer version, then we need to setup Composer in our Windows PATH. This will let you use composer command from any directory. Verify if your composer installed properly by using using the following command:

$ cd C:/
$ C:/ composer -V

Once you’re done, create a new directory in C:/, depending on what drive letter your Windows is using. It should be using C:/ as default but double-check your local install. Download https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar and save it in our new directory. Now using Visual Editor IDE or anything you are comfortable with, create a new batch file and name it wp.bat for our alias.

Save the following code on your wp.bat file:

@ECHO OFF
php "%~dp0wp-cli.phar" %*

Set the variable Path in your local environment. Go over to System Properties -> Advanced System Properties -> Advanced. Click on the Environment Variables under the System Variables and find the variable name Path. Add ;C:\WP-CLI and click save. Restart the bash interface you are using at the moment and type wp cli version.

If you can see WP-CLI 2.x.x, then it means you have successfully installed WP CLI.

Happy coding!

Categories
PHP Tutorials WordPress

How to install WordPress Coding Standard on Ubuntu

WordPress has a set of coding standards that you can use when you develop either plugins or themes. While it’s not mandatory, I highly recommend using it on your project. It will make your code more user friendly and relatively easy to maintain in the long run.

I was a Windows user for a long time and recently switched to Ubuntu 20. When I tried to install WordPress Coding Standards, I struggled a few times since I’m new to the Linux OS. In this tutorial, I will show you step by step on how I did it on my end and hoping that this will help you out.

First requirement: composer. I’m using this throughout my installation. You can check their documentation on how you install it in your system.

Installation steps:

  1. Install PHP_CodeSniffer – This is the script that is responsible for tokenization of the PHP, CSS and Javascript code on your project that detects any code violation from the defined standard. By using a terminal in Linux, cd to your home directory and install PHP_CodeSniffer.
$ cd ~/
$ composer global require "squizlabs/php_codesniffer=*"
  1. Download WordPress Coding Standard – In my case, I would prefer to install this globally instead of per project. Make sure that you are still in your home directory in your terminal before starting. Executing the code below will clone the repository and rename it wpcs.
$ git clone -b master https://github.com/WordPress/WordPress-Coding-Standards.git wpcs
  1. After you have downloaded the WordPress Coding Standard, we need to set this on your local path. Now this is the part where I have struggled before so make sure you follow exactly to avoid the mistakes I’ve made.
$ sudo phpcs --config-set installed_paths /home/username/wpcs

Noticed the username? That would be the username of your current account. You should see this path when you go to Files -> Home, then press CTRL + L. You can verify if you have working sniffers by using phpcs -i.

PHPCS values

After you have confirmed that WordPress Coding Standard is added to your setup, we can now install the extensions we need for the Visual Studio Code. There are tons of similar extensions that are currently available, but these are the extensions that I am using and proven to be working.

Phpcbf by Per Soderlind and phpcs by Ioannis Kappas

Installations of these extensions are pretty much straightforward. Once you have done that, we are going to configure the settings. I would personally recommend that we set this up globally instead of per workspace. This will save you repetitive configuration, however if you prefer per workspace setup, you can copy the same settings from below as well.

Restart your Visual Code Editor, then go to File -> Preferences -> Settings -> Extensions -> PHP CodeSniffer configuration. Scroll down a bit until you see Edit in settings.json as shown below.

Click that link and add the following:

{
   "phpcs.enable": true,
   "phpcs.executablePath": "/path/to/phpcs",
   "phpcs.standard": "WordPress",
   "phpcbf.enable": true,
   "phpcbf.documentFormattingProvider": true,
   "phpcbf.onsave": true,
   "phpcbf.executablePath": "/path/to/phpcbf",
   "phpcbf.standard": "WordPress",
   "phpcs.showSources": true,
}

Now, open a terminal then go to your home directory then we need to determine the paths for phpcbf and phpcf that we need for the configuration.

$ cd ~/
$ which phpcs
$ which phpcbf

Copy the path of both tools and put them on the executablePath value respectively. Save and restart your Visual Code Editor. By this moment, you should be able to have the tools working. Open a sample PHP file and add your code, then when you click CTRL + S, it will sniff your code by default and phpcbf will auto format your code.

Let me know in the comment section if you find this tutorial useful or if you have any questions.

Happy coding!

Categories
PHP Tutorials

Formatting Multidimensional Array in PHP

Every PHP programmer or definitively all programmers must have encountered array in respective programming languages they’re good at. Either it single or multidimensional, every array is tricky.

If you are a wordpress developer either it’s plugin or theme or simply administrator, you must have known the popular Contact Form 7 and the independent plugin associated along with it, Contact Form 7 to Database. These are two popular plugins in WordPress SVN with multi-million download hits. What Contact Form 7 does is capturing the information and save it in database before Contact Form 7 sent the email and the database design is not somewhat beginners friendly. It uses the Unix formatted timestamp as secondary key to identify the group of columns which the information belongs to.

Now, if you query the table using WPDB global class, you get those in same format as below:

Array
(
    [0] => stdClass Object
        (
            [entry_id] => 6
            [entry_time] => 1369643273
            [entry_key] => last_name
            [entry_value] => Smith
        )

    [1] => stdClass Object
        (
            [entry_id] => 5
            [entry_time] => 1369643273
            [entry_key] => first_name
            [entry_value] => John
        )

    [2] => stdClass Object
        (
            [entry_id] => 7
            [entry_time] => 1369643273
            [entry_key] => age
            [entry_value] => 26
        )

    [3] => stdClass Object
        (
            [entry_id] => 8
            [entry_time] => 1369643273
            [entry_key] => ethnicity
            [entry_value] => Caucasian
        )

    [4] => stdClass Object
        (
            [entry_id] => 9
            [entry_time] => 1369643451
            [entry_key] => first_name
            [entry_value] => Fredirick
        )

    [5] => stdClass Object
        (
            [entry_id] => 10
            [entry_time] => 1369643451
            [entry_key] => last_name
            [entry_value] => Scheidner
        )

    [6] => stdClass Object
        (
            [entry_id] => 11
            [entry_time] => 1369643451
            [entry_key] => age
            [entry_value] => 29
        )

    [7] => stdClass Object
        (
            [entry_id] => 12
            [entry_time] => 1369643451
            [entry_key] => ethnicity
            [entry_value] => European
        )

)

It’s in a form of multidimensional array. Now if you analyze the array above, you can see that these information belong to a single table entry and the entry ID is not supposedly use as information key instead just a unique key that every database required to hold unique values. Only three array key that is useful: entry_time, entry_key and entry_value. The entry_time as I’ve explain earlier is a UNIX formatted time that was stored at the time the user submit the form using either PHP strtotime or MySql NOW().

So how we format this multidimensional array into array that represent the proper information like below?

Array
(
    [1369643451] => Array
        (
            [first_name] => Fredirick
            [last_name] => Scheidner
            [age] => 29
            [ethnicity] => European
        )

)

That’s our tutorial this time. Formatting multidimensional array in PHP using same values as key. Before we start let’s take a look one more time on this reformatted array. This only good on fetching single record but how about if we’re going to fetch more than one and how we arrange those records?

Array
(
    [0] => Array
        (
            [1369643451] => Array
                (
                    [first_name] => Fredirick
                    [last_name] => Scheidner
                    [age] => 29
                    [ethnicity] => European
                )

        )

    [1] => Array
        (
            [1369643273] => Array
                (
                    [last_name] => Smith
                    [first_name] => John
                    [age] => 26
                    [ethnicity] => Caucasian
                )

        )

)

Above is what our final output will look like. We are going to create PHP function that reformat multidimensional PHP array and use the repetitive values ( in our case, entry_time ) as array key. First, create a function and named it reconstruct that accepts 4 instances: the unformatted array, array key to be used, the actual array key from unformatted array and the array values.

function reconstruct( $arrayToReconstruct, $basedKey, $entry_key, $entry_value )
{

}

Create an empty array that will hold the formatted array and we will return it in final output.

$reconstructedArray = array();

Next, determine each array key and corresponding value, then check if that key exist in array key to be used.

if( in_array( $basedKey, $arrayToReconstruct[$key] ) )
{

}

After that, create an array that output as our sample above.

$reconstructedArray[$basedKey][ $arrayToReconstruct[$key][$entry_key] ]=$arrayToReconstruct[$key][$entry_value];

And finally return the reformatted array.

return $reconstructedArray;

Our final function will be look like this:

function reconstruct( $arrayToReconstruct, $basedKey, $entry_key, $entry_value ){

		$reconstructedArray = array();

		foreach( $arrayToReconstruct as $key=>$value ){
			if( in_array( $basedKey, $arrayToReconstruct[$key] ) ){

				$reconstructedArray[$basedKey][ $arrayToReconstruct[$key][$entry_key] ]=$arrayToReconstruct[$key][$entry_value];

			}
		}
		return $reconstructedArray;

	}

It’s that simple. So how do we use this function? First determine what array key that we will use from unformatted array we have which are ” 1369643451” for Fredirick Scheidner and “1369643273” for John Smith. Then use this function while looping the array key.

$key = array( "1369643451", "1369643273" );
$new = array();

foreach( $key as $value ){
	$new[] = reconstruct( $data, $value , "entry_key", "entry_value" );
}

That’s it, that’s how simple it is in formatting multidimensional array in PHP. I hope you can learn from this.

Categories
Tutorials Visual Basic

How to create login form in VB.Net

Visual Basic 2012 also known as VB 11 or Visual Basic .NET is the latest stable release from Microsoft, which implemented on .NET Framework. In this blog entry, we’re going to teach you on how to create login form in VB.Net using Microsoft Access 2007. The reason I choose Access over SQL Server is that I’m used to this database software since my college days but don’t worry, I will post another one using SQL Server when I have time.

The first step is we’re going to create a database for storing user’s information. Open Microsoft Access and create blank database. Make sure you know where you save the file as this is important on OleDB Connection String later. Create table and name it “tbl_user”. Depending on how you design the table, the 3 most important columns are ID, username and password. I have different approach on designing my user table and you may follow it but not recommended. Add these columns: “first_name”, “last_name”, “middle_name”, “age”, “address”, “user_level”, “username”, “password”

Microsoft Office Access 2007

You must populate after creating the table as many as you can for our testing later. Nest step, open Visual Studio and create New Project for Visual Basic under Templates and select Windows Form Application. Name the application on whatever you want but I recommend letting the software do it.

1.1

After you create new project, Visual Studio will create a new form ready to use. We’re going to design this form and name it frmLogin.

1.2

Design the form same as below. Please take note of these important steps:

1.) Rename the username textbox to txtUsername and password textbox to txtPassword

2.) Rename the login button to btnLogin and cancel button to btnCancel

1.3

Double click on Login button. This will show you the coding window and your mouse focus is in inside btnLogin Click declaration as shown below.

1.4

Next step, we need to make sure that user provide both username and password so we are going to use If Else condition statement and OR comparison operator. Add this line inside btnLogin Private Sub.

' Check if username or password is empty
If txtPassword.Text = "" Or txtUsername.Text = "" Then
            MessageBox.Show("Please complete the required fields..", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
End If

We are using OR operator as it is must satisfy either one of the condition to be TRUE. So if the user enters either only username or password, error will be shown. The first statement is only a reminder of what this particular line of code is all about. Visual Basic compiler will not include this line when executing.

Notice that MessageBox.Show() has 4 arguments? It’s not required for those four completely but only for the first argument. The 1st argument is important as this will be shown to end user of whatever you have written on it. In this case, we’re going to use “Please complete the required fields..” to indicate the user that those fields are important. 2nd argument(  “Authentication Error” )is the MessageBox caption at the left side of those Minimize, Maximize and Close button at the very top. 3rd argument is the button and last one is the icon( Red X ). See the figure below.

1.5

Next step we will do the connecting to database and execute data comparison inside Else condition. Add this line after the Else statement.

' Connect to DB
            Dim conn As New System.Data.OleDb.OleDbConnection()
            conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\LibraryManagementSystem.accdb"

Please take note that the ConnectionString may vary from machine to machine. In my case, Jet Pack provider is not compatible in 64 bit machine and I use ACE OLEDB instead. To get your connection string, Follow the steps below:

1.)    Go back to design environment window and click on DataBindings in Properties window. Click F4 in you can’t see the Properties window or add it on VIEW->Properties Window.

2.)    Under DataBindings, click on Text->Add Project Data Source. This will give you Data Source Configuration wizard.

3.)    Choose Database as your Data Source Type and click Next.

4.)    Choose Dataset as your Database Model and then click Next.

5.)    Click on New Connection and you will see Add Connection window.

6.)    On the Data source, click Change and choose Microsoft Access Database File.

7.)    Now we’re going to locate the database that we created a while ago. Click on Browse and locate the database. If you create a secured database, enter your Username and Password to make a successful connection. Since this is just a tutorial, I didn’t show you on how to secure a database. However, if you’re going to develop software for distribution, you must secure your database.

8.)    Now click on Test Connection. If you have succeeded, then we’re good to go to next step.

9.)    Click OK to close the Add Connection wizard and expand the “Connection string that you will save in the application”. Copy the connection string given and paste it on conn.ConnectionString

1.6

Next step we are going to use Try and Catch the Exception. Go back to your btnLogin Private Sub and add the code below.

Try  
Catch ex As Exception
 MessageBox.Show("Failed to connect to Database.. System Error Message:  " & ex.Message, "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

The MessageBox instances are the same as the previous one except we concatenate( ampersand & ) the exception message to let us know the exact error.

Add this code inside Try.

Dim sql As String = "SELECT * FROM tbl_user WHERE username='" & txtUsername.Text & "' AND password = '" & txtPassword.Text & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)

'Open Database Connection
sqlCom.Connection = conn
conn.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()

The sql string holds the username and password comparison in SQL Statement format. Astrerisk( * ) means that we are going to fetch every column on tbl_user we’ve created earlier on matched record in WHERE condition output.  In checking the required fields earlier, we use OR comparison operator in which only one conditions must be TRUE in order to satisfy. In here, we’re going to use AND as it will proceed only if both conditions are TRUE. Meaning username and password must be matched or it will fail. The sql will be executed and store in sqlRead variable.

Next step, were going to check if user enter correct username and password in order to proceed. Create another form and name it as frmMain. When user has been authenticated, this frmMain will show and we’re going to hide the frmLogin. Otherwise, we’re going to display error message, clear username and password text box and focus the set the input focus to username text field. Add the code below.

If sqlRead.Read() Then
    frmMainForm.Show()
    Me.Hide()
Else
    ' If user enter wrong username and password combination
    ' Throw an error message
    MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

    'Clear all fields
    txtPassword.Text = ""
    txtUsername.Text = ""

    'Focus on Username field
    txtUsername.Focus()
End If

Our full code for btnLogin Private Sub will be like this:

Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
        ' Check if username or password is empty
        If txtPassword.Text = "" Or txtUsername.Text = "" Then
            MessageBox.Show("Please complete the required fields..", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            ' Both fields was supply
            ' Check if user exist in database
            ' Connect to DB
            Dim conn As New System.Data.OleDb.OleDbConnection()
            conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\LibraryManagementSystem.accdb"

            Try
                'conn.Open()
                'MsgBox("Susscess")

                Dim sql As String = "SELECT * FROM tbl_user WHERE username='" & txtUsername.Text & "' AND password = '" & txtPassword.Text & "'"
                Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)

                'Open Database Connection
                sqlCom.Connection = conn
                conn.Open()

                Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()

                If sqlRead.Read() Then
                    frmMainForm.Show()
                    Me.Hide()

                Else
                    ' If user enter wrong username and password combination
                    ' Throw an error message
                    MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

                    'Clear all fields
                    txtPassword.Text = ""
                    txtUsername.Text = ""

                    'Focus on Username field
                    txtUsername.Focus()
                End If

            Catch ex As Exception
                MessageBox.Show("Failed to connect to Database..", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try

        End If
    End Sub

Next step we are going to code the btnCancel. It depends on how you want to do with the Cancel button. Mostly, other people simply exiting the program when clicking on Cancel button but in my case, I’m going to clear username and password field text and focus the key to username. So double click on Cancel button and add the code inside the btnCancel Private Sub. Note the below code is the complete Private Sub.

Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
    'User clicking on cancel button only clears field
    ' and refocus to first field
    txtUsername.Text = ""
    txtPassword.Text = ""
    txtUsername.Focus()
End Sub

So how the login form looks like when running? Check the screenshots below.

Login form ready to use.
When user enters wrong username and password combination, warning will be shown.
When user forgets to enter both username and password, error message will be shown.

Hopefully you enjoy my little tutorial. Next, I’m going to use SQL Server instead of Access and will share it in the future.