Posts

4th TIP Student Congress with the Alumni – 2014

Hey guys! I'm sorry to disappoint you but I'm not going to publish some codes today. I was invited to be a guest speaker at our institute's student congress with the alumni - for the second time. It was held yesterday, January 23, 2014 in the Technological Institute of the Philippines, QC.

I was with my batch-mate/schoolmate Mark Kevin and Jasmine for the Information Technology student program. It's good to see them, the students, my college and professors!

Here are some of the things I remember telling our students or audience.IntroductionGood day everyone!First, I wanna thank all the organizers of this event (OSA, the Alumni Office, etc.) for inviting me here (especially Ms. Isip!) for the second time (I was invited last January 2011) to see and speak to you guys. I hope everyone is having a great day so far.We were invited here to speak to you about “where are we now?” - since the time we graduated from this institution. In my case, I will talk about the things I experienced after college, not during our college. But if you have some questions during my college life, that's really fine too.Who am I?

I want to introduce myself. My name is John Michael Vincent D. Dalisay. Such a long name right? My parents make it hard for me to write it during my elementary days.

You can call me “Mike”. I’m 23 years old, from Antipolo City. A graduate of Bachelor of Science in Information Technology batch 2010, April.Current Position and CompanyI’m currently working as a Senior Software Developer for an IT solutions provider here in Quezon City. Our company is called “Eacomm Corporation”. I have been with the company for almost three and a half years now - and I’m glad that everything is still doing great in our company.

Eacomm corporation has be around since 2001. Our company is not that big. But it is stable. We always have cool projects that you can be excited to work on.

Since I joined the company, I personally worked with  government agencies (DOLE), educational institutions (UP, Ateneo), and dozens of small and medium scale businesses (Canadian Hospitality Institute, Cafe Sweet, Calleza Grill). Business is good.

Junior Years

During my Junior years in the company, I worked mostly on client (such as the above) and company owned websites - philippinecompanies.com, eforuli.com, eacomm.com. I mostly worked with the back-end stuff such as database and web programming.I’m not a graphic or web designer. I worked with a graphic designer for every website’s visual design. I was a Junior Software Developer for over two years, from August 2010 up to December 2012.

Promotion and high pay is not in my mind. The pay is just fine for me (it increases every 3 or 6 months anyway, depending on your performance). I know I have lot to learn in my field and being a Junior Software Developer for more than two years seems so fit.

I’m happy acquiring new knowledge, improving my skills in programming and software development and everything in the real-life learning process.One Step Forward

On December 2012, I signed some new papers. I was promoted as a Software Developer. I’m not a Junior anymore. This was effective January 2013.

It was the year when I almost stopped working with client and company websites (although sometimes they need some support).2013Year 2013 was an awesome year for me. Good thing that the 2012 judgement day was cancelled. Just kidding.

It was the year when we signed with a big project - from being an experimental project. Our client is in the sales and marketing industry. He wanted to change the way we think about sales people, making them more technical and cope up with the digital age.

The project is “Software as a Service” or Saas, we are, of course, using the cloud, web and mobile technologies for this project.  I can’t tell you more about this project due to some legal issues.

I also worked with Google Singapore. I developed a data collection app to improve Google Maps. The final demo came and a product manager from Google came to the Philippines.

Her name is Ms. Autumn Zhang. She was also a former Software Engineer at Google - worked on Google Maps features like "My Maps".

You can look at her LinkedIn profile.

Below are some pictures taken during our presentation. I was the one in gray shirt, holding the Android device. Ms. Zhang is the one in pink.

Also this year, our company joined an app development contest hosted by DOTC with some sponsors like Smart communications.

Our app is called Trip Barker. Here's a preview of our app, in case you're interested.

https://youtube.com/watch?v=mmTbp77G5CE%3Fwmode%3Dopaque%26rel%3D0

We won as the champion. Below are some pictures taken during the event.

The Trip Barker Development Team and EACOMM Management along with DOTC Secretary Joseph Emilio Abaya and other organizers and sponsors of the event.

Me holding our 100K check and trophy.

We were also featured in the news, here are some.

We were also nominated to the 2014 Mobile Premier Awards at the Mobile World Congress in Barcelona, Spain this February 2014.Another Beautiful StepJust recently (December 2013), I signed some new papers again. I was promoted to a Senior Developer level effective this January 2014. I’m so happy that something good is happening in my career. I want to be a better leader and software developer.

Future Career Plans

Like what most people say, I want to have my own company, my own business. Maybe after some few more years, I’ll step into this stage of my life. The reality is, I don’t want to be an employee my whole life.

I want to build something awesome, useful to people and make my own money from it. I want to be an entrepreneur. My primary business will be in the IT field and after that, I will venture into food and real estate.

Good Advise

Be humble. If you're humble, you'll be like a sponge, absorbing lessons not only from school but also from life. If you're humble, you can always learn new things and it will make you a better person. You'll be smarter. You'll be happier. If you're humble, you will receive more, and so you can give more - it feels wonderful.

Just do it. Start doing what you have to do. You'll always figure it out. Most of us procrastinate thinking we can't do it. This is also your chance to hone your skills and sharpen you mind for the real life, or in the industry after your college studies.Good Quotes

Aside from my very inspirational and interesting story, I also want to present some awesome words from some well-known names in the tech industry. You can use it for your career.

"Your work is going to fill a large part of you life, and the only way to be truly satisfied is to do what you believe is great work." ~ Steve Jobs, Apple

"Always deliver more than expected." ~ Larry Page, Google

"When you innovate, you've go to be prepared for everyone telling you you're nuts." ~ Larry Ellison, Oracle

"What really motivates people at Facebook is building stuff they're proud of." ~ Mark Zuckerberg, Facebook

"Success is a lousy teacher. It seduces smart people into thinking they can't lose." ~ Bill Gates, Microsoft

"A brand for a company is like a reputation for a person. You earn reputation by trying to do hard things well." ~ Jeff Bezos, Amazon

Industry Testimonials

End.

Below is the power-point version of my presentation.

https://onedrive.live.com/embed?resid=C4871CC26D7FF69%21144

Alright, that was my short talk! I didn't have enough time to tell them something more since it's already 6:15 PM and 6:00 PM was the dismissal. I saw in their eyes that they want more, but the time is up.Funny moments include their interest in my love life. My power-point presentation was web based, sometimes, the internet connection is really slow so we wait for some slides to load. While loading, they wanted me to say something about my love life. I was just smiling at them and saying something else. Haha! I said we were there to encourage and tell them about the IT industry.It feels so good knowing that you have a positive impact to the lives of others. Those students, I know they listened carefully. The asked questions. I feel their interest. They are amazed. It feels like I'm giving them something to look forward too and so they will keep on moving forward!

After the talk, I was assisted by a student officer to the dining room and have a dinner with our professors, student officers, and colleagues. The food was good.

Here are some more pictures from the event.

Student officer Jason and Jasmine.

On our dinner table.

Me and Jasmine.

They also gave the alumnus some TIP stuff...

...and a certificate of appreciation.

Thanks for reading! If you're one of the students there, I hope I inspired you. Again, thanks for listening.

Generating JSON String with PHP

Today I'm going to share this code I used to generate a JSON string with data from MySQL database.

For those not yet familiar, JSON is a lightweight data interchange format (like XML but it is lightweight).

It has been used by companies like Google and Facebook in their APIs.

Recently, I needed a JSON string to get data from the web to the Android app I'm working on.

The PHP file gets a parameter company_id to select few data related to a company.

Please note that this is not a production ready code, but is very useful to get you started and can serve as quick reference.

PHP Code

Here's a short PHP code to generate JSON string. It is really easy compared to using XML.

<?php
// connection to the database
$host = "your_host";
$username = "your_username";
$password = "your_password";
$db_name = "your_database_name";

try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){
    echo "Connection error: " . $exception->getMessage();
}

// parameter
$company_id = isset($_GET['company_id']) ? $_GET['company_id'] : die();

// SQL query and prepared statement
$stmt = $con->prepare("SELECT id, name, description FROM document_sequences WHERE company_id = :company_id");
$stmt->bindParam(':company_id', $company_id);
$stmt->execute();

// get the results in array
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// you can remove this line if you want
$results = array('DocumentSequence' => $results);

// now show the json tring
echo json_encode($results);
?>

Viewing JSON String

The PHP code above generates JSON string that may cause real pain in your heart, it looks like this:

{"DocumentSequence":[{"id":"4","name":"Store two","description":"Document sequence for store 2."},{"id":"5","name":"Store One","description":"Document Sequence for store 1."},{"id":"6","name":"Store 3","description":"Document sequence for store three."}]}

But the good news is, there's an excellent JSON viewer online that we can use for a better JSON vieweing. It is called Online JSON Viewer.

You just have to copy your JSON string (or load via URL) to the "Text" tab and then click the "Viewer" tab. JSON string above will now look like this:

generate-json-string-with-php

Optimize Image for Web Using Photoshop and Thoughts on Faster Web Pages

This post is supposed to be a quick-tip on how you can optimize your images for web pages. But it feels like I also want to give some thoughts about website speed. There are many websites saying that your images must be optimized for the web, that should be updated and say, "your images must be optimized for web and mobile devices" in which the amazing Adobe Photoshop can help us with.

But before the tutorial and showing you the amazing results, I just want to give some thoughts on faster web pages. Optimizing your images can benefit, youyour users and search engines such as Google.

WEBSITE OWNER

I love fast loading web pages. Over a month ago, Alexa says this website's load time is around 4 to 6 seconds. That's horrible. So I decided to make this website load faster. Here are some of the things I've done to make it possible:

  1. I removed Infolinks ads to achieve speed in exchange for few bucks.
  2. I removed my Twitter and Google plus follow buttons.
  3. I removed Facebook like box, it loads images of Facebook users which is slow. The one you're seeing on the right sidebar is just an optimized image.
  4. I removed some jQuery plugins such as the "Recent Posts" plugin, the one you're seeing in the right sidebar is just a hard coded HTML.
  5. I limited "Related Posts" plugin to show just 5 items. Each item is a callback that makes a slow page load.
  6. I removed my stylesheet hosted in Google drive. Google drive HTML/CSS hosting is really slow.
  7. In short, lessen your HTTP requests.

Now a page from this site loads around 1 to 2 seconds. They say that it should be 1.5 seconds or less. But for now, the current speed is just okay for me. I'm still looking for ways to improve it, it's just I don't have much time for that yet.

YOUR VISITORS

You readers or website visitors also love your website to be fast even though you won't hear them saying it to your face. Everyone loves instant nowadays, instant noodles, instant result, etc. The same with web pages, users wants to read, or should I say scan, your content and get what's in your brain in an instant. One way to do this is making your web pages load fast.

GOOGLE

What you and your users love, Google love. If your visitors like their experience to your site, they might share it or link back to it. And Google can see it, which can give your website a chance to rank higher in search results. Currently, around 80% of this site's traffic comes from Google. Thank you Google!

HOW TO OPTIMIZE AN IMAGE FOR WEB AND DEVICES USING PHOTOSHOP?

Easy. Watch the video I made for you below

THE RESULT.

I chose to have a 'high' quality image. So from 80 kilobytes, it becomes 14 kilobytes.Here's the 80 kilobytes version:

...and now here's the 14 kilobytes version.

As for my eyes, it makes almost no difference aside from it's file size which is more than 4x smaller compared to the original. You can download the two images above and view their properties. Or you can do the few easy steps on the video above to see for yourself.I think this is a nice start for making your web pages load faster, and as always, thanks for reading!

12 jQuery Questions and Answers You Should Be Reading on StackOverflow

Hi guys! Below are twelve of the jQuery related questions and answers on StackOverflow that I found very useful during development. I opted to compile them here because I feel good reading those brilliant questions and answers by coders from around the world. Enjoy!

  1. How would I know if an element is hidden?

Sometimes you want some elements of your page to be visible, and if it is not visible, you want to tell the user about it. For example, a user must have a selection of data first before proceeding to new operation. If he has no selection (div is hidden), you can do a prompt that he must select something.

  1. How do I get selected text in select box?

Ah, a drop-down list? Link # 2 above shows you how to get the user drop down list selection.

  1. How to redirect a page?

Useful if you want to your users to see a page after an AJAX request, or you just want them to be redirected. I’ve written another example here, jQuery: Redirect onClick

  1. How would I know if a checkbox is checked or unchecked?

For example, you want to enable a delete button if the user selected at least one data to delete, else, the delete button is disabled. I’ve written another example here: Check or Uncheck Checkboxes with jQuery And Get Selected with PHP

  1. How to select a child element?

Teaches us how to select a child element and do it with faster performance (see the comment by Paul Irish).

  1. event.preventDefault() vs. return false

I use return false; when I want to prevent a page refresh after clicking a submit button and doing an AJAX request.

  1. Example of using jQuery .closest() method.

I use jQuery .closest() method on selecting an element within a table with several rows. I probably have to write an example in another blog post, ha!

  1. How would I know the existence of an element?

Useful if you want to perform something if an element exists in your page. The faster way is using if ($(selector).length) {}

  1. How would I know which radio button is selected?

This is how you will know if a user is a male or female, using jQuery!

  1. How to select multiple classes?

Sometimes you want to to something to multiple classes at once. There’s another example here.

  1. How to select an element by its name, not by class or id?

If you’re more familiar with an element’s name or don’t want to add a class or id name, you can use this cool technique.

  1. What if Google hosted jQuery is blocked?

In some countries, Google’s domain name is banned. So if you are using a Google hosted jQuery library, you’re site won’t work. Link # 12 above shows you the fall back.

This can be the first part of the list, you can add more in the comments section below, or on our Facebook, Twitter or Google+!
And as always, thanks for reading!

Email Activation Code in PHP

Email activation or verification is one requirement when you’re building an app with a membership feature. Our Email Activation Code in PHP will help you with that!

This is one way to detect if there’s really a person behind the submitted email address. An email address is considered invalid if no person was able to open it and click the activation link.

Although nowadays, there are some alternative ways to verify the validity of an email address or user. Some systems prefer the old school method, like what this post covers.

Email Activation Code in PHP

OAuth

The alternative way I was talking about is by using a social network login. Facebook, Twitter, Google+ and even Microsoft is providing something called an OAuth (Open Authorization) login.

In simple scenario, have you ever seen a "Login with Facebook" button? We see one in StackOverflow login:

oauth-login-email-validation

Unfortunately, we don't cover OAuth login in this post.

Basic Flow

The following steps shows the basic flow how email activation works.

  1. User fills up your sign up or registration form and submit it to the system.
  2. System generates unique activation code which acts like a “key”
  3. System sends a link with the activation code to the email provided during the sign up form.
  4. User opens his email inbox, found the system email and click the link with the activation code. This is like using the “key” to “unlock the door” which represents your application.
  5. User was sent to a link saying ‘email was activated’

Where are these happening?

To give you a clearer picture where in our code the steps above happens:

Steps 1 to 3 happens in sign_up.php.

Step 4 happens in the user’s email provider such as GMail, Y! Mail, etc. User should receive something like this:

email-verification-link-sent

Step 5 happens in our activate.php

Let’s Code!

Alright, so the technologies used in this code are mostly PHP and MySQL.

Create your database and name it 'email_activation_db'. Here’s the database table structure that can be used, we name it as the ‘users’ table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nickname` varchar(32) NOT NULL,
  `email` varchar(264) NOT NULL,
  `verified` int(11) NOT NULL COMMENT '0=no, 1=yes',
  `verification_code` varchar(264) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
 
INSERT INTO `users` (`id`, `nickname`, `email`, `verified`, `verification_code`, `created`, `modified`) VALUES
(135, '', '[email protected]', 1, '2e729fe3ded03c139b289213db2b3159', '2016-08-13 16:42:28', '2016-08-13 08:42:46');

libs/db_connect.php – for database connection, this file has the following code:

<?php
$host = "localhost";
$db_name = "email_activation_db";
$username = "root";
$password = "";
 
try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
    echo "Connection error: " . $exception->getMessage();
}
?>

sign_up.php – where the sign up form and processing of user input is located. The following code is inside sign_up.php file.

<?php
// if the sign up form was submitted
if($_POST){
 
    $email = isset($_POST['email']) ? $_POST['email'] : "";
 
    // posted email must not be empty
    if(empty($email)){
        echo "<div>Email cannot be empty.</div>";
    }
 
    // must be a valid email address
    else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        echo "<div>Your email address is not valid.</div>";
    }
 
    else{
 
        include 'libs/db_connect.php';
 
        // check first if record exists
        $query = "SELECT id FROM users WHERE email = ? and verified = '1'";
        $stmt = $con->prepare( $query );
        $stmt->bindParam(1, $email);
        $stmt->execute();
        $num = $stmt->rowCount();
 
        if($num>0){
            echo "<div>Your email is already activated.</div>";
        }
 
        else{
 
            // check first if there's unverified email related
            $query = "SELECT id FROM users WHERE email = ? and verified = '0'";
            $stmt = $con->prepare( $query );
            $stmt->bindParam(1, $email);
            $stmt->execute();
            $num = $stmt->rowCount();
 
            if($num>0){
 
                // you have to create a resend verification script
                echo "<div>Your email is already in the system but not yet verified.</div>";
            }
 
            else{
 
                // now, compose the content of the verification email, it will be sent to the email provided during sign up
                // generate verification code, acts as the "key"
                $verificationCode = md5(uniqid("yourrandomstringyouwanttoaddhere", true));
 
                // send the email verification
                $verificationLink = "https://codeofaninja.com/demos/php-examples/email-activation-php-script/activate.php?code=" . $verificationCode;
 
                $htmlStr = "";
                $htmlStr .= "Hi " . $email . ",<br /><br />";
 
                $htmlStr .= "Please click the button below to verify your subscription and have access to the download center.<br /><br /><br />";
                $htmlStr .= "<a href='{$verificationLink}' target='_blank' style='padding:1em; font-weight:bold; background-color:blue; color:#fff;'>VERIFY EMAIL</a><br /><br /><br />";
 
                $htmlStr .= "Kind regards,<br />";
                $htmlStr .= "<a href='https://codeofaninja.com/' target='_blank'>The Code of a Ninja</a><br />";
 
 
                $name = "The Code of a Ninja";
                $email_sender = "[email protected]";
                $subject = "Verification Link | The Code Of A Ninja | Subscription";
                $recipient_email = $email;
 
                $headers  = "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                $headers .= "From: {$name} <{$email_sender}> \n";
 
                $body = $htmlStr;
 
                // send email using the mail function, you can also use php mailer library if you want
                if( mail($recipient_email, $subject, $body, $headers) ){
 
                    // tell the user a verification email were sent
                    echo "<div id='successMessage'>A verification email were sent to <b>" . $email . "</b>, please open your email inbox and click the given link so you can login.</div>";
 
 
                    // save the email in the database
                    $created = date('Y-m-d H:i:s');
 
                    //write query
                    $query = "INSERT INTO
                                users
                            SET
                                email = ?,
                                verification_code = ?,
                                created = ?,
                                verified = '0'";
 
                    $stmt = $con->prepare($query);
 
                    $stmt->bindParam(1, $email);
                    $stmt->bindParam(2, $verificationCode);
                    $stmt->bindParam(3, $created);
 
                    // Execute the query
                    if($stmt->execute()){
                        // echo "<div>Unverified email was saved to the database.</div>";
                    }else{
                        echo "<div>Unable to save your email to the database.";
                        //print_r($stmt->errorInfo());
                    }
 
                }else{
                    die("Sending failed.");
                }
            }
 
 
        }
 
    }
 
}
 
// show your sign up or registration form
echo "<form action='" . $_SERVER['PHP_SELF'] . "' method='post'>";
    echo "<input type='email' name='email' placeholder='Enter your email address to subscribe' required />";
    echo "<input type='submit' value='Subscribe' />";
echo "</form>";
?>

For sending the verification email, we used the PHP mail() function but you can also use a library like PHPMailer if you want to use SMTP such as of GMail.

activate.php – it has one job, update the the unverified to verified email address.

<?php
include 'libs/db_connect.php';
 
// check first if record exists
$query = "SELECT id FROM users WHERE verification_code = ? and verified = '0'";
$stmt = $con->prepare( $query );
$stmt->bindParam(1, $_GET['code']);
$stmt->execute();
$num = $stmt->rowCount();
 
if($num>0){
 
    // update the 'verified' field, from 0 to 1 (unverified to verified)
    $query = "UPDATE users
                set verified = '1'
                where verification_code = :verification_code";
 
    $stmt = $con->prepare($query);
    $stmt->bindParam(':verification_code', $_GET['code']);
 
    if($stmt->execute()){
        // tell the user
        echo "<div>Your email is valid, thanks!. You may now login.</div>";
    }else{
        echo "<div>Unable to update verification code.</div>";
        //print_r($stmt->errorInfo());
    }
 
}else{
    // tell the user he should not be in this page
    echo "<div>We can't find your verification code.</div>";
}
?>

Live Demo

Please note that this demo is live. If you enter your email and click the subscribe button, you will receive an email with the activation link. If you click it, you will be subscribed here in our code blog.

Download Email Activation Code in PHP

You can get the source code by following the whole, well detailed tutorial above.

But isn’t it more convenient if you can just download the complete source code we used, and play around it?

The source code of this tutorial is part of our 30+ useful Web Programming source code package. Each item in the package has its own tutorial like the one above.

If you are just starting out to learn web programming and serious about learning more, this is the right package for you. Click green button below to see the what is included in the package and download it there.


Need email activation code only? But the code now using the green button below.

Related Source Code

You can download our PHP Login System & User Management Module as well. This source code is about PHP Login System.

It will help you understand how to login and logout functionality works. Sign up email verification, user registration, and forgot password features are included as well.

Thanks for studying our email activation code in PHP!

Fixed: Cannot send session cache limiter – headers already sent

Okay, so many of you guys still ask me about how to fix these warning messages in our Facebook scripts. Today I'm going to give you two possible fixes that you can do. By the way, here's the warning message we want to remove:

FIX IT BY ADDING A SESSION_START()

You can fix it by adding a session_start() on top of your PHP file, just right after your first line <?php tag. It looks like this:

FIX IT BY MOVING FACEBOOK INSTANCE

You can fix it by moving the Facebook class and instance code on top of your PHP file. It would look like this:

If none of them worked, you can read more here.

CakePHP 2.x Pagination Tutorial: Helper, Conditions, Limit, Sorting and More!

CakePHP Pagination is one of the fastest thing you can code with this amazing framework. In this post I’m gonna show you how you can create a pagination script in matter of few minutes, or even seconds! Cool? Let’s get started.

This post is part of my CakePHP tutorial series, before you proceed to this, make sure you already installed your CakePHP poperly, know the CakePHP classes and naming conventions, and much better if you can code the CakePHP CRUD operations.

Video Demo

Here’s a video demo of what will be our code ouput.

Controller Code

On our controller, we are going to have a query the cakePHP way, we are going to have the following conditions:

  • Won’t include the record with an ID of 6 (‘conditions’ => array(‘User.id !=’ => ’6′))
  • We will limit to 3 records per page (‘limit’ => 3)
  • Order the result by ID (‘order’ => array(‘id’ => ‘desc’)) in descending order

So here’s the code that will be added in our UsersController.php

public function view() {
 
    // we prepare our query, the cakephp way!
    $this->paginate = array(
        'conditions' => array('User.id !=' => '6'),
        'limit' => 3,
        'order' => array('id' => 'desc')
    );
     
    // we are using the 'User' model
    $users = $this->paginate('User');
     
    // pass the value to our view.ctp
    $this->set('users', $users);
     
}

The $users variable gives us an array that look like this:

cakephp-pagination

View Code

On our view.ctp, our data is presented with a table. The table header contains the paginator sort() method for sorting the data using any fields you want (and you won’t have to create another query!)

The $this->Paginator object (pagination helper) also has lots of methods for paging, please see the ‘pagination section’ on the code block below.

Also we used the <div class=’paging’> which uses the CakePHP generic CSS. You can change that if you want and be creative with your paging UI design.

<?php
// so we use the paginator object the shorter way.
// instead of using '$this->Paginator' everytime, we'll use '$paginator'
$paginator = $this->Paginator;
 
if($users){
 
    //creating our table
    echo "<table>";
 
        // our table header, we can sort the data user the paginator sort() method!
        echo "<tr>";
         
            // in the sort method, ther first parameter is the same as the column name in our table
            // the second parameter is the header label we want to display in the view
            echo "<th>" . $paginator->sort('id', 'ID') . "</th>";
            echo "<th>" . $paginator->sort('firstname', 'Firstname') . "</th>";
            echo "<th>" . $paginator->sort('lastname', 'Lastname') . "</th>";
            echo "<th>" . $paginator->sort('username', 'Username') . "</th>";
        echo "</tr>";
         
        // loop through the user's records
        foreach( $users as $user ){
            echo "<tr>";
                echo "<td>{$user['User']['id']}</td>";
                echo "<td>{$user['User']['firstname']}</td>";
                echo "<td>{$user['User']['lastname']}</td>";
                echo "<td>{$user['User']['username']}</td>";
            echo "</tr>";
        }
         
    echo "</table>";
 
    // pagination section
    echo "<div class='paging'>";
 
        // the 'first' page button
        echo $paginator->first("First");
         
        // 'prev' page button, 
        // we can check using the paginator hasPrev() method if there's a previous page
        // save with the 'next' page button
        if($paginator->hasPrev()){
            echo $paginator->prev("Prev");
        }
         
        // the 'number' page buttons
        echo $paginator->numbers(array('modulus' => 2));
         
        // for the 'next' button
        if($paginator->hasNext()){
            echo $paginator->next("Next");
        }
         
        // the 'last' page button
        echo $paginator->last("Last");
     
    echo "</div>";
     
}
 
// tell the user there's no records found
else{
    echo "No users found.";
}
?>

Thanks for reading this tutorial code for pagination in CakePHP!

Creating Social Media Icons for Your Website using CSS

In almost every website we see today, there are links to their social media accounts. I think it is a standard now. It’s like, you’re not cool if you don’t have a Facebook and Twitter account!

Recently, I was using Google drive to host my CSS and image files. Now, I removed it. Why?

Because Google drive slows down my website! During the use of Google drive hosted CSS and images, the average load time of this wesbite is around 10-20 seconds for new visitors.

After I removed it, it is now around less than 5 seconds!

Creating Social Media Icons for Your Website using CSS
My new social media icons. :)

I decided not to use any third party CSS code. I wanted to create my own social media icons, and I did! (see the screenshot above or the lower right corner of this page for live demo)

I think the icons I made are so cute that I thought of sharing it to you guys (I appreciate a tweet, like or +1 before you use it!). It loads fast, contains few lines of CSS and HTML code, and it doesn’t use any images! Here’s how I did it, below are the CSS and HTML code I used.

HTML code:

<div id="socialMediaIcons">
 
    <a class="facebook" href="https://www.facebook.com/CodeOfANinja" title="Facebook" target="_blank">f</a>
     
    <a class="twitter" href="http://twitter.com/ninjazhai" title="Twitter" target="_blank">t</a>
     
    <a class="googleplus" href="https://plus.google.com/b/101266899643014043497/101266899643014043497/posts" title="Google+" target="_blank">g+</a>
     
    <a class="rss" href="https://www.codeofaninja.com/feeds/posts/default?alt=rss" title="RSS" target="_blank">r</a>
     
    <a class="email" href="http://feedburner.google.com/fb/a/mailverify?uri=TheCodeOfANinja" title="Email" target="_blank">@</a>
     
</div>

CSS code:

#socialMediaIcons{
    margin: 0 auto;
    text-align:center;
}
 
#socialMediaIcons a{
    border-radius: 3px;
    color:#fff;
    font-family: arial;
    font-size:1em;
    height:2.5em;
    padding:1em;
    text-align:center;
    width:2.5em;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
}
 
#socialMediaIcons a:hover{
    color:#fff;
    text-decoration:none;
}
 
.facebook { background:#4c66a4; padding:2px 10px; }
.twitter { background:#33bcef; padding:2px 10px; }
.googleplus { background:#D2412E; padding:2px 3px; }
.rss { background:#fa9b39; padding: 2px 6px; }
.email { background:#00D8CC; padidng: 2px 6px; }

And… that’s how I created my new social media icons using CSS!