Tải bản đầy đủ (.pdf) (316 trang)

Lập trình PHP 7 programming blueprints

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (11.22 MB, 316 trang )

CuuDuongThanCong.com

www.allitebooks.com
/>

PHP 7 Programming Blueprints
Learn how to exploit the impressive power of PHP 7
with this collection of practical project blueprints –
begin building better applications for the web today!

Jose Palala
Martin Helmich

BIRMINGHAM - MUMBAI

CuuDuongThanCong.com

www.allitebooks.com
/>

PHP 7 Programming Blueprints
Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the authors, nor Packt Publishing, and its
dealers and distributors will be held liable for any damages caused or alleged to be caused
directly or indirectly by this book.


Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: October 2016
Production reference: 2061016

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-971-4
www.packtpub.com

CuuDuongThanCong.com

www.allitebooks.com
/>

Credits
Authors

Copy Editor

Jose Palala
Martin Helmich

Safis Editing

Reviewer


Project Coordinator

Shuvankar Sarkar

Ulhas Kambali

Commissioning Editor

Proofreader

Kunal Parikh

Safis Editing

Acquisition Editor

Indexer

Chaitanya Nair

Rekha Nair

Content Development Editor

Production Coordinator

Onkar Wani

Melwyn Dsa


Technical Editor

Cover Work

Murtaza Tinwala

Melwyn Dsa

CuuDuongThanCong.com

www.allitebooks.com
/>

About the Authors
Jose Palala has been working professionally with PHP for at least 8 years. He has
experience working with PHP frameworks such as Eden PHP, CodeIgniter, Laravel and
Zend.
He has worked for Philippine-based IT companies for at least 8 years, working on projects
ranging from internal corporate systems and CMS websites. In his spare time, he regularly
contributes back to the tech community in the Philippines.
I would like to thank everyone at Packt Publishing, it’s been great working with them since
Day 1. Super thanks to all to my colleagues, friends and family who have helped me to
become a better developer and have helped me become what I am today.

Martin Helmich holds a Master's degree in Computer Science from the University of
Applied Sciences in Osnabrück. He works as a software architect and specializes in building
distributed applications using web technologies and Microservice Architectures. Besides
programming in Go, PHP, Python and Node.JS, he also builds infrastructures using
configuration management tools like SaltStack and container technologies like Docker.

He is an open source enthusiast and likes to make fun of people who are not using Linux. In
his free time, you'll probably find him coding on one of his open source pet projects,
listening to music or reading science-fiction literature.

CuuDuongThanCong.com

www.allitebooks.com
/>

About the Reviewer
Shuvankar Sarkar is an IT analyst and experienced in C#, .NET, PHP and web
development.
He is a technology enthusiast and maintains his blog at You can
follow him on Twitter at @sonu041. He is interested in computer security as well.
I would like to thank my family for making my life easier and full of happiness.

CuuDuongThanCong.com

www.allitebooks.com
/>

www.PacktPub.com
eBooks, discount offers, and more
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters and receive exclusive discounts and offers on Packt books and
eBooks.


/>
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser

CuuDuongThanCong.com

www.allitebooks.com
/>

Table of Contents
Preface
Chapter 1: Create a User Profile System and use the Null Coalesce
Operator
The null coalesce operator
Separation of Concerns
Creating views
Create a profile input form
Admin system
Summary

Chapter 2: Build a Database Class and Simple Shopping Cart
Building the database abstraction class
Raw query method
Create method

Read method
Select all method
Delete method
Update method
first_of method
last_of method
iterate_over method
searchString method
Using the convert_to_json method to implement a simple API
Shopping Cart
Building the shopping items list
Item template rendering function

Adding checkboxes to the Shopping List page
Cookies in PHP
Building the Checkout page
Thank you page
Installing TCPDF
Admin for managing purchases
Summary

Chapter 3: Building a Social Newsletter Service

CuuDuongThanCong.com

www.allitebooks.com
/>
1
6
7

8
8
10
13
17
18
19
19
19
20
20
21
21
22
22
22
22
23
23
24
24
27
28
29
32
33
38
40
41



Authentication system
Creating a social login for members
Member dashboard
Marketers dashboard
Administration system for managing marketers

Custom template for our newsletter
Link tracking
AJAX socket chat for support
Introduction to socket.io

Summary

Chapter 4: Build a Simple Blog with Search Capability using
Elasticsearch
Creating the CRUD and admin system
Seeding the post table
What is Elasticsearch?
Installing Elasticsearch and the PHP client
Building a PHP Elasticsearch tool

Adding documents to our Elasticsearch
Querying Elasticsearch
Installing Logstash
Setting up the Logstash configuration
Installing PHP Redis
Encoding and decoding JSON messages

Storing Apache logs in Elasticsearch

Getting filtered data to display with Highcharts

Dashboard app for viewing Elasticsearch logs
Simple search engine with result caching
Cache basics
Cache invalidation of Redis data

Using browser localStorage as cache
Working with streams
Storing and searching XML documents using PHP
Using Elasticsearch to search a social network database
Displaying randomized search engine results

Summary

Chapter 5: Creating a RESTful Web Service
RESTful basics
REST architectures
Common HTTP methods and response codes
First steps with the Slim framework
[ ii ]

CuuDuongThanCong.com

www.allitebooks.com
/>
41
47
52
56

57
60
63
66
66
73
75
75
80
80
81
85
87
88
88
89
89
91
92
93
99
101
103
103
104
106
108
108
110
112

113
114
114
115
116


Installing Slim
A small sample application
Accepting URL parameters

Accepting HTTP requests with a message body
The PSR-7 standard
Middleware
Implementing the REST service
Designing the service
Bootstrapping the project
Building the persistence layer with MongoDB
Adding and retrieving users
Listing and searching users
Deleting profiles
Validating input
Streams and large files
Profile image upload
Using GridFS storage
Summary

Chapter 6: Building a Chat Application
The WebSocket protocol
First steps with Ratchet

Architectural considerations
Getting started
Testing WebSocket applications
Playing with the event loop
Implementing the chat application
Bootstrapping the project server-side
Bootstrapping the HTML user interface
Building a simple chat application
Receiving messages
Sending messages
Testing the application
Keeping the connection from timing out
Deployment options
Bridging Ratchet and PSR-7 applications
Accessing your application via the web server
Adding authentication
Creating the login form
Checking the authorization
[ iii ]

CuuDuongThanCong.com

www.allitebooks.com
/>
116
117
118
119
120
122

124
124
125
127
132
137
140
143
145
145
149
152
153
153
154
154
155
158
159
162
162
164
165
170
171
171
172
173
176
182

183
184
188


Connecting users and messages
Summary

190
192

Chapter 7: Building an Asynchronous Microservice Architecture
The target architecture
ZeroMQ patterns
Request/reply pattern
Publish/subscribe pattern
Push/pull pattern
Bootstrapping the project
Building the inventory service
Getting started with ZeroMQ REQ/REP sockets
Using JsonRPC for communication
Making the inventory service multithreaded
Building the checkout service
Using react/zmq
Working with promises
Building the mailing service
Building the shipping service
PUSH/PULL for beginners
Fan-out/fan-in
Bridging ZeroMQ and HTTP

Summary

Chapter 8: Building a Parser and Interpreter for a Custom Language
How interpreters and compilers work
Languages and grammars
Your first PEG parser
Evaluating expressions
Building an Abstract Syntax Tree
Building a better interface
Evaluating variables
Adding logical expressions
Comparisons
The “and” and “or” operators
Conditions
Working with structured data
Working with objects
Optimizing the interpreter by adding a compiler
Verifying performance improvements
[ iv ]

CuuDuongThanCong.com

/>
193
193
195
195
196
196
197

198
198
200
205
209
209
211
219
223
223
228
230
236
237
238
239
242
246
249
254
256
259
260
263
265
268
271
273
281



Summary

285

Chapter 9: Reactive Extensions in PHP

286

An introduction to observables
Introduction to event loop and ReactiveX
delay
defer
Scheduler
recursive-scheduler
map and flatMap
reduce
toArray
merge
do
scan
zip
Parsing logs through a Reactive scheduler
Event queues with ReactiveX
Summary

Index

286
287

289
289
290
290
292
292
293
294
294
295
296
297
298
299
300

[v]

CuuDuongThanCong.com

/>

Preface
PHP is a great language for developing web applications. It is essentially a server-side
scripting language that is also used for general-purpose programming. PHP 7 is the latest
version, which provides major backward-compatibility breaks and focuses on providing
improved performance and speed. With the rise in demand for high performance,
this newest version contains everything you need to build efficient applications. PHP 7
provides improved engine execution, better memory usage, and a better set of tools
allowing you to maintain high traffic on your websites with low-cost hardware and servers

through a multithreading web server.

What this book covers
Chapter 1, Create a User Profile System and use the Null Coalesce Operator, we'll discover new

PHP 7 features and build app for storing user profiles.

Chapter 2, Build a Database Class and Simple Shopping Cart, we'll create a simple database

layer library which will help us access our database. We'll cover some tips on making our
queries secure, and how to make our coding simpler and more succinct with PHP 7.
Chapter 3, Building a Social Newsletter Service, we'll be building a social newsletter service,

which will have a way for users to sign in using their social login and allow them to register
to a newsletter. We'll also make a simple admin system for managing the newsletters.
Chapter 4, Build a Simple Blog with Search Capability using Elasticsearch, you will learn how to

create a blog system, experiment with ElasticSearch and how to apply it in your code. Also,​
you will learn how to create a simple blog application and store data into MySQL.
Chapter 5, Creating a RESTful Web Service, shows you how create a RESTful web service

that can be used to manage user profiles. The service will be implemented using the Slim
micro framework and use a MongoDB database for persistence. The chapter also covers the
basics of RESTful web services, most importantly the common HTTP request and response
methods, the PSR-7 standard and PHP 7’s new mongodb extension.

CuuDuongThanCong.com

/>


Preface
Chapter 6, Building a Chat Application, describes the implementation of a real-time chat

application using WebSockets. You will learn how to use the Ratchet framework to build
stand-alone WebSocket and HTTP servers with PHP and how to connect to WebSocket
servers in a JavaScript client application. We will also discuss how you can implement
authentication for WebSocket applications and how to deploy them in a production
environment.
Chapter 7, Building an Asynchronous Microservice Architecture, covers the implementation of

a (small) microservice architecture. Instead of RESTful web services, you will use ZeroMQ
in this chapter for network communication, an alternative communication protocol that
focuses on asynchronicity, loose coupling and high performance.
Chapter 8, Building a Parser and Interpreter for a Custom Language, describes how to use the

PHP-PEG library to define a grammar and implement a parser for a custom expression
language that can be used to add end-user development features to enterprise applications.
Chapter 9, Reactive Extensions in PHP, here we'll look into the Reactive extensions library

for PHP, and and try to build a simple scheduled app.

What you need for this book
You’ll need to download and install PHP 7 from the official PHP website. You’ll also need
to install a Webserver such as Apache or Nginx configured to run PHP 7 by default.
If you are experienced with virtual machines, you can also use Docker containers and/or
Vagrant to build an environment with PHP 7 installed.

Who this book is for
The book is for web developers, PHP consultants, and anyone who is working on multiple
projects with PHP. Basic knowledge of PHP programming is assumed.


Conventions
In this book, you will find a number of text styles that distinguish between different kinds
of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Let's
create a simple UserProfile class."
[2]

CuuDuongThanCong.com

/>

Preface

A block of code is set as follows:
function fetch_one($id) {
$link = mysqli_connect('');
$query = "SELECT * from ". $this->table . " WHERE `id` =' " .
$results = mysqli_query($link, $query);
}

$id "'";

When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
'credit_card' => $credit_card,
'items' => //<all the items and prices>//,
'total' => $total,


Any command-line input or output is written as follows:
mysql> source insert_profiles.sql

New terms and important words are shown in bold. Words that you see on the screen, for
example, in menus or dialog boxes, appear in the text like this: "Simply click on Allow
access and then click on OK."
Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or disliked. Reader feedback is important for us as it helps us
develop titles that you will really get the most out of.
To send us general feedback, simply e-mail , and mention the
book's title in the subject of your message.

[3]

CuuDuongThanCong.com

/>

Preface

If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you

to get the most from your purchase.

Downloading the example code
You can download the example code files for this book from your account at http://www.p
acktpub.com. If you purchased this book elsewhere, you can visit ktpub.c
om/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
1.
2.
3.
4.
5.
6.
7.

Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's
webpage at the Packt Publishing website. This page can be accessed by entering the book's
name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at />ishing/PHP-7-Programming-Blueprints. We also have other code bundles from our rich
catalog of books and videos available at Check
them out!

[4]

CuuDuongThanCong.com

/>

Preface

Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used
in this book. The color images will help you better understand the changes in the output.
You can download this file from />l o a d s / P H P 7 P r o g r a m m i n g B l u e p r i n t s _ C o l o r I m a g e s . p d f.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books—maybe a mistake in the text or the
code—we would be grateful if you could report this to us. By doing so, you can save other
readers from frustration and help us improve subsequent versions of this book. If you find
any errata, please report them by visiting />selecting your book, clicking on the Errata Submission Form link, and entering the details
of your errata. Once your errata are verified, your submission will be accepted and the
errata will be uploaded to our website or added to any list of existing errata under the
Errata section of that title.
To view the previously submitted errata, go to />t/support and enter the name of the book in the search field. The required information will
appear under the Errata section.


Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At
Packt, we take the protection of our copyright and licenses very seriously. If you come
across any illegal copies of our works in any form on the Internet, please provide us with
the location address or website name immediately so that we can pursue a remedy.
Please contact us at with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable
content.

Questions
If you have a problem with any aspect of this book, you can contact us
at , and we will do our best to address the problem.

[5]

CuuDuongThanCong.com

/>

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.

CuuDuongThanCong.com

/>

Create a User Profile System and use the Null Coalesce Operator

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` =' " .
$results = mysqli_query($link, $query);
}

$id "'";

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;

[7]

CuuDuongThanCong.com


/>

Create a User Profile System and use the Null Coalesce Operator
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>';
}
}

Separation of Concerns
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.

Creating views
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.

[8]

CuuDuongThanCong.com

/>

Create a User Profile System and use the Null Coalesce Operator

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>
href=" />">
</head>
<body>
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 features, 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

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.
1. To supply data to 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');

[9]

CuuDuongThanCong.com

/>


Create a User Profile System and use the Null Coalesce Operator

2. 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

3. Then type use <name of database>:
mysql>

use <database>;

4. Import the script by running the source command:
mysql> source insert_profiles.sql

Now our user profiles page should show the following:

Create a profile input form
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">

[ 10 ]


CuuDuongThanCong.com

/>

Create a User Profile System and use the Null Coalesce Operator
<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);
}
}

[ 11 ]

CuuDuongThanCong.com

/>

Create a User Profile System and use the Null Coalesce Operator

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'] has been set, that the user
that we will be fetching from the database and displaying on the form. Here is how that

code will look like:
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>

exit;

[ 12 ]

CuuDuongThanCong.com

/>

Create a User Profile System and use the Null Coalesce Operator
}

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.

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><td>-->

×