Categories
Tutorials WordPress

Advanced Custom Fields (ACF): A Deep Dive

Advanced Custom Fields (ACF) is one of the most popular WordPress plugins for creating and managing custom fields. With ACF, developers can enhance WordPress’s flexibility, transforming it from a blogging platform into a robust content management system (CMS). This article explores ACF in depth, providing insights, use cases, and code examples to help you harness its full potential.

Key Features of ACF

ACF offers numerous features that make it an indispensable tool for developers:

  1. Custom Field Types: From simple text fields to advanced repeaters and flexible content fields, ACF supports a wide range of input types.
  2. Conditional Logic: Display fields based on user-defined conditions.
  3. Integration with REST API: ACF fields can be exposed via the WordPress REST API for headless WordPress projects.
  4. Ease of Use: ACF provides a user-friendly interface, making it accessible to both developers and non-technical users.
  5. Gutenberg Compatibility: ACF allows the creation of custom Gutenberg blocks with its Block API.

Setting Up ACF

To get started with ACF:

  1. Install the plugin via the WordPress Plugin Repository or upload it manually.
  2. Navigate to Custom Fields in the WordPress dashboard.
  3. Create a new field group and define fields within it.
  4. Assign the field group to specific post types, pages, or taxonomies.

Example PHP Code:

if (function_exists('acf_add_local_field_group')) {
    acf_add_local_field_group(array(
        'key' => 'group_example',
        'title' => 'Example Fields',
        'fields' => array(
            array(
                'key' => 'field_text',
                'label' => 'Text Field',
                'name' => 'text_field',
                'type' => 'text',
            ),
        ),
        'location' => array(
            array(
                array(
                    'param' => 'post_type',
                    'operator' => '==',
                    'value' => 'post',
                ),
            ),
        ),
    ));
}

Insights into ACF Usage

  1. Dynamic Templates: Retrieve and display ACF fields in theme templates using get_field() or the_field().
  2. Flexible Layouts: Use repeater and flexible content fields to build dynamic layouts.
  3. Custom Post Type Integration: Pair ACF with custom post types for structured content.
  4. Global Options: Create global settings accessible across the entire site using ACF options pages.
  5. Headless WordPress: Use ACF fields in conjunction with the REST API or WPGraphQL for decoupled applications.

Real-World Use Cases

  1. Team Member Profiles: Use ACF to create editable profiles for a team directory.
  2. Event Schedules: Build an events page with custom fields for date, time, and location.
  3. Product Specifications: Enhance WooCommerce products with additional specifications fields.
  4. Portfolio Showcases: Display portfolio items with galleries, project details, and client testimonials.
  5. Custom Page Builders: Enable clients to design unique pages with flexible content fields.

Example: Team Member Profile Template

if (have_rows('team_members')): 
    echo '<div class="team">';
    while (have_rows('team_members')): the_row();
        echo '<div class="member">';
        echo '<h2>' . get_sub_field('name') . '</h2>';
        echo '<p>' . get_sub_field('role') . '</p>';
        echo '</div>';
    endwhile;
    echo '</div>';
endif;

Integration with Gutenberg

ACF’s Block API simplifies creating custom blocks for the WordPress Block Editor (Gutenberg). Define the block settings in PHP and use a template for rendering.

Example PHP Code:

if (function_exists('acf_register_block_type')) {
    acf_register_block_type(array(
        'name' => 'custom-block',
        'title' => __('Custom Block'),
        'render_template' => 'template-parts/blocks/custom-block.php',
        'category' => 'formatting',
        'icon' => 'admin-comments',
        'keywords' => array('custom', 'block'),
    ));
}

Best Practices

  1. Field Naming: Use clear, descriptive names for fields.
  2. Documentation: Document field usage for maintainability.
  3. Version Control: Store field definitions in code for version control.
  4. Performance: Limit the number of fields to avoid performance bottlenecks.

Common Challenges and Solutions

  1. Field Not Displaying: Ensure the field group is assigned correctly.
  2. Performance Issues: Optimize by caching results of get_field().
  3. REST API Compatibility: Use the ACF to REST API plugin to expose custom fields.

Conclusion

ACF is a game-changer for WordPress development, enabling the creation of dynamic, data-driven websites. By leveraging its features, developers can build solutions tailored to unique client requirements. Whether you’re creating custom layouts, enhancing WooCommerce functionality, or building a headless WordPress site, ACF provides the tools you need to succeed.

Categories
PHP Tutorials WordPress

Mastering WordPress Customization: A Guide for Intermediate Users

WordPress is one of the most versatile content management systems available, and its customization options are virtually limitless. For intermediate users looking to elevate their websites, understanding advanced customization techniques is key. This article delves into three essential aspects of WordPress customization: child themes, custom templates, and theme frameworks. By mastering these techniques, you’ll be able to craft a website that stands out both in functionality and design.

Understanding Child Themes

A child theme is a sub-theme that inherits the functionality, features, and style of a parent theme. The primary advantage of using a child theme is the ability to modify or add to a theme’s functionality without losing your changes when the parent theme is updated.

Creating a child theme involves a few simple steps. First, create a new folder in your WordPress themes directory and give it a name that reflects your customization project. Inside this folder, you’ll need two files: style.css and functions.php. The style.css file should include a header specifying the template of the parent theme. For example:

/*
Theme Name: My Child Theme
Template: parent-theme-folder-name
*/

In the functions.php file, enqueue the parent theme’s stylesheet by adding the following code:

<?php
function my_child_theme_styles() {
    wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');
}
add_action('wp_enqueue_scripts', 'my_child_theme_styles');
?>

Once your child theme is activated, you can start customizing by overriding template files from the parent theme or adding new functionality.

Customizing with Child Themes

One of the most common uses for child themes is to customize styles and layouts. By adding custom CSS to your style.css file or overriding specific parent theme templates in the child theme folder, you can tweak designs to suit your needs. For instance, if the parent theme includes a header.php file and you need a custom header, copying that file into your child theme directory and editing it allows you to safely implement your changes.

For more advanced customizations, you can use the functions.php file to add hooks and filters. This enables you to modify WordPress core functions or extend the functionality of the parent theme without directly editing its files.

Creating Custom Page Templates

Custom page templates are an excellent way to create unique layouts for specific pages on your site. WordPress makes this process straightforward. Start by creating a new PHP file in your theme or child theme directory. At the top of the file, include the following header:

<?php
/*
Template Name: Custom Template
*/
?>

Once saved, this template will appear in the “Page Attributes” section of the WordPress editor under the “Template” dropdown.

Custom templates allow you to define specific layouts and functionality for individual pages. For example, you could create a landing page template with no header or footer, optimized for conversions. Use WordPress functions like get_header() and get_footer() to include standard elements, and add custom HTML, PHP, or even JavaScript to build your desired layout.

Enhancing Functionality with Custom Templates

Custom templates aren’t limited to aesthetics. They can also serve functional purposes. For instance, you can create a template that queries specific posts, integrates a third-party API, or displays a custom form. By using WordPress’s template hierarchy and conditional tags, you can fine-tune how content is displayed and ensure your site meets its specific goals.

Exploring Theme Frameworks

Theme frameworks are pre-designed, feature-rich templates that serve as a foundation for building highly customized websites. Popular frameworks like Genesis, Divi, and Elementor Pro provide powerful tools and libraries to streamline the customization process.

Genesis Framework, for example, is renowned for its clean code, SEO optimization, and robust support community. It includes child themes designed for various niches, allowing you to quickly set up a site and focus on customization. Divi, on the other hand, offers a visual drag-and-drop builder, making it ideal for users who prefer a no-code approach while still having advanced control over design and layout.

Leveraging Theme Frameworks for Customization

Frameworks offer numerous advantages for intermediate users. With Genesis, you can use hooks and filters to modify almost any aspect of the theme. For Divi, you can combine its visual builder with custom CSS or JavaScript for enhanced flexibility. These frameworks also come with extensive documentation and tutorials, making them accessible even to those new to their tools.

Comparing Child Themes and Frameworks

While child themes are ideal for modifying a specific theme, frameworks provide a broader foundation for building entirely new designs. Choosing between the two often depends on your project’s scope. For minor adjustments to an existing theme, a child theme is sufficient. For more complex projects requiring unique functionality and scalability, a framework may be the better choice.

Best Practices for WordPress Customization

  1. Use a Staging Site: Always test your customizations on a staging site before applying them to your live site.
  2. Backup Your Site: Regular backups ensure you can quickly recover from errors.
  3. Document Your Changes: Keep notes on the files and code you modify for easier maintenance.
  4. Follow Coding Standards: Adhere to WordPress coding standards for cleaner, more reliable code.
  5. Test for Compatibility: Ensure your customizations are compatible with plugins and core updates.

Conclusion

WordPress customization empowers you to create a website tailored to your exact needs. By understanding and leveraging child themes, custom templates, and theme frameworks, intermediate users can unlock the full potential of WordPress. Whether you’re fine-tuning an existing theme or building a site from scratch, these tools and techniques provide the flexibility and control necessary to bring your vision to life. Start experimenting today, and take your WordPress skills to the next level!

Categories
Tutorials WordPress

How to Install WordPress and Set Up Your First Website

WordPress is one of the most popular platforms for building websites, thanks to its user-friendly interface, flexibility, and powerful features. Whether you’re setting up a personal blog, a portfolio, or an online store, WordPress can handle it all. This step-by-step guide will walk you through installing WordPress and setting up your first website.

Step 1: Choose a Domain Name and Hosting Provider

The first step to setting up your WordPress website is selecting a domain name—your website’s address (e.g., www.yourwebsite.com). Choose a name relevant to your content, representing your brand or persona. Once you have your domain name in mind, you’ll need a hosting provider to store your website’s files and make it accessible online. Popular hosting providers often offer WordPress-optimized plans with easy installation options.

Step 2: Install WordPress

Most hosting providers offer a one-click WordPress installation feature. Log into your hosting account, navigate to the control panel (cPanel), and find the WordPress installer. Follow the on-screen instructions to complete the installation. If your host doesn’t offer this feature, you can manually install WordPress by downloading it from WordPress.org, uploading the files to your server via FTP, and running the installation script.

Step 3: Configure WordPress Settings

After installation, you can access your WordPress dashboard by visiting www.yourwebsite.com/wp-admin and logging in with your credentials. Once logged in, head to the “Settings” menu to configure basic options such as your site title, tagline, timezone, and language. This is also a good time to ensure your website’s permalinks are optimized for SEO by selecting the “Post Name” option under the “Permalinks” settings.

Step 4: Choose and Install a Theme

Your website’s design and layout are controlled by your chosen theme. WordPress offers thousands of free and premium themes to suit various purposes. To browse themes, go to “Appearance” > “Themes” in the dashboard. Click “Add New” to search for themes and preview them before installing. Once you find a theme you like, click “Install” and then “Activate” to apply to your website.

Step 5: Install Essential Plugins

Plugins extend the functionality of your WordPress site. To add plugins, go to “Plugins” > “Add New” in the dashboard. Search for plugins that suit your needs—for example, Yoast SEO for search engine optimization, WooCommerce for eCommerce, or Contact Form 7 for contact forms. Always install reputable plugins and keep them updated to ensure optimal performance and security.

Step 6: Create Essential Pages

Every website should have a few key pages, such as a “Home” page, an “About” page, a “Contact” page, and any other pages relevant to your niche. To create a new page, go to “Pages” > “Add New” in the dashboard. Use the WordPress block editor to add content, images, and other elements. Publish the page when you’re satisfied with its appearance.

Step 7: Customize Your Site’s Appearance

WordPress makes it easy to customize your website without touching a single line of code. Navigate to “Appearance” > “Customize” to access the Customizer. Here, you can adjust your site’s colors, fonts, header image, and more. Some themes offer additional customization options, so explore your theme’s settings for further tweaks.

Step 8: Set Up Your Navigation Menu

A well-structured navigation menu helps visitors find their way around your site. To create a menu, go to “Appearance” > “Menus.” Add your desired pages to the menu, arrange them in the order you prefer, and assign the menu to a location (e.g., the main menu or footer). Save your changes to apply the menu to your site.

Step 9: Test Your Website

Before launching your website, test it thoroughly to ensure everything works as expected. Check for broken links, test forms, and view your site on different devices to ensure it’s mobile-friendly. Use tools like Google PageSpeed Insights to check your site’s loading speed and make improvements if needed.

Step 10: Launch Your Website

Once you’re satisfied with your website, it’s time to launch! Share your site with friends, family, and your target audience. Promote it on social media, optimize it for search engines, and monitor its performance using tools like Google Analytics.

Congratulations—you’ve successfully installed WordPress and set up your first website! With regular updates, engaging content, and ongoing optimization, your site can grow and thrive in the online world.

Categories
Tutorials WordPress

How to Make Your WordPress Site More Secure

In today’s digital landscape, a secure website is essential for protecting your data and maintaining your online reputation. WordPress is one of the most popular content management systems, but it can also be a target for hackers and malicious attacks. Fortunately, there are several proven strategies to enhance the security of your WordPress site. Here’s how to make your WordPress site secure:

1. Use Strong Passwords and User Permissions

One of the simplest yet most effective ways to secure your WordPress site is to use strong passwords and define proper user permissions:

  • Strong Passwords: Ensure every user has a unique and strong password. Use a combination of upper and lower-case letters, numbers, and special characters.
  • User Permissions: Limit user access levels based on roles. For instance, don’t give out admin access to users who do not need it.

2. Keep WordPress Core, Themes, and Plugins Updated

Software updates are crucial for security. Regularly updating the WordPress core, themes, and plugins helps protect your site from vulnerabilities:

  • Updates: Enable automatic updates if available, or check for updates frequently to ensure you’re running the latest versions.
  • Delete Inactive Plugins and Themes: If you’re not using them, it’s best to remove them to reduce potential vulnerabilities.

3. Implement a Web Application Firewall (WAF)

A Web Application Firewall is a barrier between your website and potential threats. It filters and monitors HTTP traffic to and from your site. Consider:

  • Cloud-based WAFs: Services like Sucuri or Cloudflare offer cloud-based firewalls that can mitigate risks before they reach your site.
  • Application-level WAFs: Some security plugins include firewalls that can protect against common attacks, such as SQL injection and cross-site scripting (XSS).

4. Use Security Plugins

There are numerous security plugins available that can help monitor and enhance your site’s protection. Some popular ones include:

  • Wordfence Security: A complete security solution, including firewall protection and malware scanning.
  • iThemes Security: Focuses on fixing common vulnerabilities and implementing various security measures.

5. Enable Two-Factor Authentication (2FA)

Two-factor authentication adds an extra layer of security by requiring a second form of verification:

  • Setup: Many WordPress security plugins allow you to enable 2FA with just a few clicks.
  • Benefits: Even if a user’s password is compromised, the additional verification step can help prevent unauthorized access.

6. Regular Backups

In case of an attack or data loss, having a recent backup of your site is invaluable:

  • Backup Solutions: Use backup plugins like UpdraftPlus or BackupBuddy to schedule regular backups.
  • Offsite Storage: Store backups in a secure location, such as cloud storage or an external hard drive, to prevent loss in case of server failure.

7. Implement SSL Certificates

An SSL certificate encrypts data between your server and users. Here’s why you need it:

  • Data Protection: SSL protects sensitive data exchanged on your site, such as login details and payment information.
  • SEO Benefits: Search engines favor secure sites, which can positively impact your rankings.

8. harden Your wp-config.php File

Your wp-config.php file contains critical configuration settings for your WordPress site. You can enhance its security by:

  • Restricting File Permissions: Set the file permissions to read-only (440 or 400) to prevent unauthorized access.

9. Limit Login Attempts

Limiting login attempts can prevent brute force attacks on your site:

  • Brute Force Protection: Use plugins like Limit Login Attempts Reloaded to restrict how many times a user can try to log in.
  • Lockout Feature: After a certain number of failed attempts, you can temporarily lock the user out.

10. Monitor Your Site for Threats

Regularly monitor your site for threats and vulnerabilities to stay ahead of potential attackers:

  • Security Audits: Conduct periodic security audits to identify vulnerabilities.
  • Activity Logs: Use plugins that log user activity to trace any unauthorized actions.

Conclusion

Securing your WordPress site is an ongoing process that requires vigilance and proactive measures. By implementing the strategies outlined above, you can significantly reduce the risk of an attack and protect your data and reputation. Always stay informed about the latest security trends and practices to keep your site secure in an evolving digital landscape.

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.