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.