Book Image

PHP 7 Programming Blueprints

By : Jose Palala, Martin Helmich
Book Image

PHP 7 Programming Blueprints

By: Jose Palala, Martin Helmich

Overview of this book

When it comes to modern web development, performance is everything. The latest version of PHP has been improvised and updated to make it easier to build for performance, improved engine execution, better memory usage, and a new and extended set of tools. If you’re a web developer, what’s not to love? This guide will show you how to make full use of PHP 7 with a range of practical projects that will not only teach you the principles, but also show you how to put them into practice. It will push and extend your skills, helping you to become a more confident and fluent PHP developer. You’ll find out how to build a social newsletter service, a simple blog with a search capability using Elasticsearch, as well as a chat application. We’ll also show you how to create a RESTful web service, a database class to manage a shopping cart on an e-commerce site and how to build an asynchronous microservice architecture. With further guidance on using reactive extensions in PHP, we’re sure that you’ll find everything you need to take full advantage of PHP 7. So dive in now!
Table of Contents (15 chapters)
PHP 7 Programming Blueprints
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Preface
4
Build a Simple Blog with Search Capability using Elasticsearch

Admin system


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 ($base_url, $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.

Tip

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>