Chapter 1.  Create a User Profile System and use the Null Coalesce Operator

To begin this chapter, let's check out the new null coalesce in PHP 7. We'll also learn how to build a simple profiles page with listed users that you can click on, and create a simple CRUD-like system which will enable us to register new users to the system and delete users for banning purposes.

We'll learn to use the PHP 7 null coalesce operator so that we can show data if there is any, or just display a simple message if there isn't any.

Let's create a simple UserProfile class. The ability to create classes has been available since PHP 5.

A class in PHP starts with the word class, and the name of the class:

class UserProfile { 
 
  private $table = 'user_profiles'; 
  
} 
 
} 

We've made the table private and added a private variable, where we define which table it will be related to.

Let's add two functions, also known as a method, inside the class to simply fetch the data from the database:

function fetch_one($id) { 
  $link = mysqli_connect(''); 
  $query = "SELECT * from ". $this->table . " WHERE `id` =' " .  $id "'"; 
  $results = mysqli_query($link, $query); 
} 
 
function fetch_all() { 
  $link = mysqli_connect('127.0.0.1', 'root','apassword','my_dataabase' ); 
  $query = "SELECT * from ". $this->table . "; 
 $results = mysqli_query($link, $query); 
} 

The null coalesce operator

We can use PHP 7's null coalesce operator to allow us to check whether our results contain anything, or return a defined text which we can check on the views, this will be responsible for displaying any data.

Let's put this in a file which will contain all the define statements, and call it:

//definitions.php 
define('NO_RESULTS_MESSAGE', 'No results found'); 
 
require('definitions.php'); 
function fetch_all() { 
   ...same lines ... 
   
   $results = $results ??  NO_RESULTS_MESSAGE; 
   return $message;    
} 

On the client side, we'll need to come up with a template to show the list of user profiles.

Let's create a basic HTML block to show that each profile can be a div element with several list item elements to output each table.

In the following function, we need to make sure that all values have been filled in with at least the name and the age. Then we simply return the entire string when the function is called:

function profile_template( $name, $age, $country ) { 
 $name = $name ?? null; 
  $age = $age ?? null; 
  if($name == null || $age === null) { 
    return 'Name or Age need to be set';  
   } else { 
 
    return '<div> 
 
         <li>Name: ' . $name . ' </li> 
 
         <li>Age: ' . $age . '</li> 
 
         <li>Country:  ' .  $country . ' </li> 
 
    </div>'; 
  } 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.82.154