In this article by Jose Palala and Martin Helmich, author of PHP 7 Programming Blueprints, will show you how to build a simple profiles page with listed users which 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.
(For more resources related to this topic, see here.)
You will learn to use the PHP 7 null coalesce operator so that you 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);
}
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.
Lets 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>';
}
}
In a proper MVC architecture, we need to separate the view from the models that get our data, and the controllers will be responsible for handling business logic.
In our simple app, we will skip the controller layer since we just want to display the user profiles in one public facing page. The preceding function is also known as the template render part in an MVC architecture.
While there are frameworks available for PHP that use the MVC architecture out of the box, for now we can stick to what we have and make it work.
PHP frameworks can benefit a lot from the null coalesce operator. In some codes that I've worked with, we used to use the ternary operator a lot, but still had to add more checks to ensure a value was not falsy.
Furthermore, the ternary operator can get confusing, and takes some getting used to. The other alternative is to use the isSet function. However, due to the nature of the isSet function, some falsy values will be interpreted by PHP as being a set.
Now that we have our model complete, a template render function, we just need to create the view with which we can look at each profile.
Our view will be put inside a foreach block, and we'll use the template we wrote to render the right values:
//listprofiles.php
<html>
<!doctype html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<?php
foreach($results as $item) {
echo profile_template($item->name, $item->age, $item->country;
}
?>
</body>
</html>
Let's put the code above into index.php.
While we may install the Apache server, configure it to run PHP, install new virtual hosts and the other necessary featuress, and put our PHP code into an Apache folder, this will take time, so, for the purposes of testing this out, we can just run PHP's server for development.
To run the built-in PHP server (read more at http://php.net/manual/en/features.commandline.webserver.php) we will use the folder we are running, inside a terminal:
php -S localhost:8000
If we open up our browser, we should see nothing yet—No results found. This means we need to populate our database.
If you have an error with your database connection, be sure to replace the correct database credentials we supplied into each of the mysql_connect calls that we made.
To supply data into our database, we can create a simple SQL script like this:
INSERT INTO user_profiles ('Chin Wu', 30, 'Mongolia');
INSERT INTO user_profiles ('Erik Schmidt', 22, 'Germany');
INSERT INTO user_profiles ('Rashma Naru', 33, 'India');
Let's save it in a file such as insert_profiles.sql. In the same directory as the SQL file, log on to the MySQL client by using the following command:
mysql -u root -p
Then type use <name of database>:
mysql> use <database>;
Import the script by running the source command:
mysql> source insert_profiles.sql
Now our user profiles page should show the following:
Now let's create the HTML form for users to enter their profile data.
Our profiles app would be no use if we didn't have a simple way for a user to enter their user profile details.
We'll create the profile input form like this:
//create_profile.php
<html>
<body>
<form action="post_profile.php" method="POST">
<label>Name</label><input name="name">
<label>Age</label><input name="age">
<label>Country</label><input name="country">
</form>
</body>
</html>
In this profile post, we'll need to create a PHP script to take care of anything the user posts. It will create an SQL statement from the input values and output whether or not they were inserted.
We can use the null coalesce operator again to verify that the user has inputted all values and left nothing undefined or null:
$name = $_POST['name'] ?? "";
$age = $_POST['country'] ?? "";
$country = $_POST['country'] ?? "";
This prevents us from accumulating errors while inserting data into our database.
First, let's create a variable to hold each of the inputs in one array:
$input_values = [
'name' => $name,
'age' => $age,
'country' => $country
];
The preceding code is a new PHP 5.4+ way to write arrays. In PHP 5.4+, it is no longer necessary to put an actual array(); the author personally likes the new syntax better.
We should create a new method in our UserProfile class to accept these values:
Class UserProfile {
public function insert_profile($values) {
$link = mysqli_connect('127.0.0.1', 'username','password', 'databasename');
$q = " INSERT INTO " . $this->table . " VALUES ( '". $values['name']."', '".$values['age'] . "' ,'". $values['country']. "')";
return mysqli_query($q);
}
}
Instead of creating a parameter in our function to hold each argument as we did with our profile template render function, we can simply use an array to hold our values.
This way, if a new field needs to be inserted into our database, we can just add another field to the SQL insert statement.
While we are at it, let's create the edit profile section.
For now, we'll assume that whoever is using this edit profile is the administrator of the site.
We'll need to create a page where, provided the $_GET['id'] or has been set, that the user that we will be fetching from the database and displaying on the form.
<?php
require('class/userprofile.php');//contains the class UserProfile into
$id = $_GET['id'] ?? 'No ID';
//if id was a string, i.e. "No ID", this would go into the if block
if(is_numeric($id)) {
$profile = new UserProfile();
//get data from our database
$results = $user->fetch_id($id);
if($results && $results->num_rows > 0 ) {
while($obj = $results->fetch_object())
{
$name = $obj->name;
$age = $obj->age;
$country = $obj->country;
}
//display form with a hidden field containing the value of the ID
?>
<form action="post_update_profile.php" method="post">
<label>Name</label><input name="name" value="<?=$name?>">
<label>Age</label><input name="age" value="<?=$age?>">
<label>Country</label><input name="country" value="<?=country?>">
</form>
<?php
} else {
exit('No such user');
}
} else {
echo $id; //this should be No ID';
exit;
}
Notice that we're using what is known as the shortcut echo statement in the form. It makes our code simpler and easier to read. Since we're using PHP 7, this feature should come out of the box.
Once someone submits the form, it goes into our $_POST variable and we'll create a new Update function in our UserProfile class.
Let's finish off by creating a simple grid for an admin dashboard portal that will be used with our user profiles database. Our requirement for this is simple: We can just set up a table-based layout that displays each user profile in rows.
From the grid, we will add the links to be able to edit the profile, or delete it, if we want to. The code to display a table in our HTML view would look like this:
<table>
<tr>
<td>John Doe</td>
<td>21</td>
<td>USA</td>
<td><a href="edit_profile.php?id=1">Edit</a></td>
<td><a href="profileview.php?id=1">View</a>
<td><a href="delete_profile.php?id=1">Delete</a>
</tr>
</table>
This script to this is the following:
//listprofiles.php
$sql = "SELECT * FROM userprofiles LIMIT $start, $limit ";
$rs_result = mysqli_query ($sql); //run the query
while($row = mysqli_fetch_assoc($rs_result) {
?>
<tr>
<td><?=$row['name'];?></td>
<td><?=$row['age'];?></td>
<td><?=$row['country'];?></td>
<td><a href="edit_profile.php?id=<?=$id?>">Edit</a></td>
<td><a href="profileview.php?id=<?=$id?>">View</a>
<td><a href="delete_profile.php?id=<?=$id?>">Delete</a>
</tr>
<?php
}
There's one thing that we haven't yet created: A delete_profile.php page. The view and edit pages - have been discussed already.
Here's how the delete_profile.php page would look:
<?php
//delete_profile.php
$connection = mysqli_connect('localhost','<username>','<password>', '<databasename>');
$id = $_GET['id'] ?? 'No ID';
if(is_numeric($id)) {
mysqli_query( $connection, "DELETE FROM userprofiles WHERE id = '" .$id . "'");
} else {
echo $id;
}
i(!is_numeric($id)) {
exit('Error: non numeric $id');
} else {
echo "Profile #" . $id . " has been deleted";
?>
Of course, since we might have a lot of user profiles in our database, we have to create a simple pagination. In any pagination system, you just need to figure out the total number of rows, and how many rows you want displayed per page. We can create a function that will be able to return a URL that contains the page number and how many to view per page.
From our queries database, we first create a new function for us to select only up to the total number of items in our database:
class UserProfile{
// …. Etc …
function count_rows($table) {
$dbconn = new mysqli('localhost', 'root', 'somepass', 'databasename');
$query = $dbconn->query("select COUNT(*) as num from '". $table . "'");
$total_pages = mysqli_fetch_array($query);
return $total_pages['num']; //fetching by array, so element 'num' = count
}
For our pagination, we can create a simple paginate function which accepts the base_url of the page where we have pagination, the rows per page — also known as the number of records we want each page to have — and the total number of records found:
require('definitions.php');
require('db.php'); //our database class
Function paginate ($baseurl, $rows_per_page, $total_rows) {
$pagination_links = array(); //instantiate an array to hold our html page links
//we can use null coalesce to check if the inputs are null
( $total_rows || $rows_per_page) ?? exit('Error: no rows per page and total rows);
//we exit with an error message if this function is called incorrectly
$pages = $total_rows % $rows_per_page;
$i= 0;
$pagination_links[$i] = "<a href="http://". $base_url . "?pagenum=". $pagenum."&rpp=".$rows_per_page. ">" . $pagenum . "</a>";
}
return $pagination_links;
}
This function will help display the above page links in a table:
function display_pagination($links) {
$display = ' <div class="pagination">';
<table><tr>';
foreach ($links as $link) {
echo "<td>" . $link . "</td>";
}
$display .= '</tr></table></div>';
return $display;
}
Notice that we're following the principle that there should rarely be any echo statements inside a function. This is because we want to make sure that other users of these functions are not confused when they debug some mysterious output on their page.
By requiring the programmer to echo out whatever the functions return, it becomes easier to debug our program. Also, we're following the separation of concerns—our code doesn't output the display, it just formats the display.
So any future programmer can just update the function's internal code and return something else. It also makes our function reusable; imagine that in the future someone uses our function—this way, they won't have to double check that there's some misplaced echo statement within our functions.
A note on alternative short tags
As you know, another way to echo is to use the <?= tag. You can use it like so: <?="helloworld"?>.These are known as short tags. In PHP 7, alternative PHP tags have been removed. The RFC states that <%, <%=, %> and <script language=php> have been deprecated. The RFC at https://wiki.php.net/rfc/remove_alternative_php_tags says that the RFC does not remove short opening tags (<?) or short opening tags with echo (<?=).
Since we have laid out the groundwork of creating paginate links, we now just have to invoke our functions. The following script is all that is needed to create a paginated page using the preceding function:
$mysqli = mysqli_connect('localhost','<username>','<password>', '<dbname>');
$limit = $_GET['rpp'] ?? 10; //how many items to show per page default 10;
$pagenum = $_GET['pagenum']; //what page we are on
if($pagenum)
$start = ($pagenum - 1) * $limit; //first item to display on this page
else
$start = 0; //if no page var is given, set start to 0
/*Display records here*/
$sql = "SELECT * FROM userprofiles LIMIT $start, $limit ";
$rs_result = mysqli_query ($sql); //run the query
while($row = mysqli_fetch_assoc($rs_result) {
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['age']; ?></td>
<td><?php echo $row['country']; ?></td>
</tr>
<?php
}
/* Let's show our page */
/* get number of records through */
$record_count = $db->count_rows('userprofiles');
$pagination_links = paginate('listprofiles.php' , $limit, $rec_count);
echo display_pagination($paginaiton_links);
The HTML output of our page links in listprofiles.php will look something like this:
<div class="pagination"><table>
<tr>
<td> <a href="listprofiles.php?pagenum=1&rpp=10">1</a> </td>
<td><a href="listprofiles.php?pagenum=2&rpp=10">2</a> </td>
<td><a href="listprofiles.php?pagenum=3&rpp=10">2</a> </td>
</tr>
</table></div>
As you can see, we have a lot of use cases for the null coalesce.
We learned how to make a simple user profile system, and how to use PHP 7's null coalesce feature when fetching data from the database, which returns null if there are no records. We also learned that the null coalesce operator is similar to a ternary operator, except this returns null by default if there is no data.
Further resources on this subject: