0% found this document useful (0 votes)
6 views85 pages

10.7 Creates Dynamic Web Pages Using PHP and MySQL

The document explains the differences between static and dynamic web pages, highlighting that static pages display the same content for all users while dynamic pages can change content based on user interactions. It introduces PHP as a server-side scripting language that enables the creation of dynamic web content and outlines its capabilities, including data handling and user interaction. Additionally, it covers basic PHP syntax, variables, control structures, loops, and data types, providing examples for better understanding.

Uploaded by

pedroishere4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views85 pages

10.7 Creates Dynamic Web Pages Using PHP and MySQL

The document explains the differences between static and dynamic web pages, highlighting that static pages display the same content for all users while dynamic pages can change content based on user interactions. It introduces PHP as a server-side scripting language that enables the creation of dynamic web content and outlines its capabilities, including data handling and user interaction. Additionally, it covers basic PHP syntax, variables, control structures, loops, and data types, providing examples for better understanding.

Uploaded by

pedroishere4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 85

10.

7 CREATES DYNAMIC
WEB PAGES USING PHP
AND MYSQL

PRACTICAL BOOK
WHAT ARE STATIC AND DYNAMIC
WEB PAGES .
• Websites are separated into two different types: static and
dynamic.
• Static websites are ones that are fixed and display the
same content for every user, usually written exclusively in
HTML.
• A dynamic website, on the other hand, is one that can
display different content and provide user interaction, by
making use of advanced programming and databases in
addition to HTML. As you can tell, static websites are
easier to create, while dynamic websites require more
work.
WHAT IS A STATIC WEBSITE?

• Static
websites usually come with a fixed number of pages that have
a specific layout.
When the page runs on a browser, the content is literally static
and doesn’t change in response to user actions. A static
website is usually created with HTML and CSS in simple text
editors like Notepad.
WHAT IS A DYNAMIC WEBSITE?

• Compared to static websites, which are purely informational, a


dynamic website is more functional. It allows users to interact
with the information that is listed on the page. Of course, that
requires utilizing more than just HTML code.
• Static websites use only client-side HTML and CSS code while
dynamic websites rely on both client-side and server-side
scripting languages such as JavaScript, PHP, or ASP.
• When a user accesses a dynamic website, the site can be
changed through code that is run in the browser and/or on
the server.
• The end result is the same as that on a static website: an
HTML page displayed on the web browser.
WHAT IS SERVER SIDE AND CLIENT-
SIDE SCRIPTING LANGUAGES
• A client-side script is a program that is processed within the client
browser. These kinds of scripts are small programs which are downloaded,
compiled and run by the browser.
• A server-side script is processed on the web server when the user
requests information. These kinds of scripts can run before a web page is
loaded. They are needed for anything that requires dynamic data, such as
storing user login details.
• Some common server-side languages include PHP, Python, Ruby and Java.

• When a server-side script is processed, the request is sent to the server


and the result is sent back to the client. This is useful for websites which
store large amounts of data, such as search engines or social networks -
it would be very slow for the client browser to download all the data.
• Scripting language php -> .php -> browser s/w like Firefox
• Programming language visual studio -> .exe
INTRODUCTION TO DYNAMIC WEB CONTENT

• Web pages can be either static or dynamic. ... Other types of Web
pages, such as PHP, ASP, and JSP pages are dynamic Web pages.
These pages contain "server-side" code, which allows the server to
generate unique content each time the page is loaded
WHAT IS PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open-source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
WHAT IS A PHP FILE?

• PHP files can contain text, HTML, CSS, and PHP code
• PHP code is executed on the server, and the result is returned to the browser as plain HTML
• PHP files have extension ".php"
WHAT CAN PHP DO?

• PHP can generate dynamic page content


• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
PHP CAN COLLECT FORM DATA

Google form
Name _________________ DB server
Age __________________
Address ______________

SUBMIT
WHY PHP?

• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)


• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP supports a wide range of databases
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side
BASIC PHP SYNTAX
• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>

<?php
// PHP code goes here
?>

• The default file extension for PHP files is ".php".


• A PHP file normally contains HTML tags, and some PHP scripting code.
BELOW, WE HAVE AN EXAMPLE OF A
SIMPLE PHP FILE, WITH A PHP SCRIPT
THAT USES A BUILT-IN PHP FUNCTION
"ECHO" TO OUTPUT THE TEXT "HELLO
WORLD!" ON A WEB PAGE:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
OUTPUT

My first PHP page


Hello World!
PHP ECHO STATEMENTS
• Used to output data to the screen.
• The echo statement can be used with or without parentheses:
echo or echo().
EXAMPLE
<!DOCTYPE html>
<html>
<body>
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
?>
</body>
</html>
OUTPUT
PHP is Fun!
Hello world!
I'm about to learn PHP!
A client-side script is a program that is processed within the client browser.

A server-side script is processed on the web server when the user requests
information.
EX:- server-side languages include PHP, Python, Ruby and Java.
INSTALL PHP
• Install PHP - PHP
• Install a web server - Apache
• Install a database - MySQL
PHP COMMENTS
• A comment in PHP code is a line that is not executed as a part of the program.
• Its only purpose is to be read by someone who is looking at the code.

<?php
// This is a single-line comment

# This is also a single-line comment

/*This is a multiple-lines comment block


that spans over multiple
lines */
?>
CREATING (DECLARING) PHP VARIABLES
• In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
• After the execution of the statements above,
• the variable $txt will hold the value Hello world!,
• the variable $x will hold the value 5,
• the variable $y will hold the value 10.5.
• When you assign a text value to a variable, put quotes around the value.
PHP VARIABLES
• A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).

Rules for PHP variables:


1. A variable starts with the $ sign, followed by the name of the variable
2. A variable name must start with a letter or the underscore character
3. A variable name cannot start with a number
4. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, _ )
5. Variable names are case-sensitive ($age and $AGE are two different variables)
Cannot have spaces inside a variable name ( ($C A T) X ($C_A_T) ✓ )
EXAMPLE
EXAMPLE
PHP VARIABLES
Output Variables
Example <?php
<?php $x = 5;
$txt = “ICT”; $y = 4;

echo "I love $txt !"; echo $x + $y;


?>
?>
Output
9
Output –
I love ICT !
EXAMPLE

<?php
$x = 5;
$y = 4;
echo $x + $y;
?>

Output
9
WHAT IS A CONTROL STRUCTURE?
• In simple terms, a control structure allows you to control the
flow of code execution in your application.
• Generally, a program is executed sequentially, line by line, and a
control structure allows you to alter that flow, usually depending
on certain conditions.
• Control structures are core features of the PHP language that
allow your script to respond differently to different inputs or
situations.
• This could allow your script to give different responses based on
user input, file contents, or some other data.
PHP SUPPORTS A NUMBER OF DIFFERENT
CONTROL STRUCTURES:

• If
• If else
• If elseif
• while
• do-while
• for
PHP IF STATEMENT
• The if construct allows you to execute a piece of code if the expression provided
along with it evaluates to true.

<?php
$age = 50;
if ($age > 30)
{
echo "Your age is greater than 30!";
}
?>
PHP IF ELSE STATEMENT
• You always use the else statement in conjunction with an if statement.
<?php
$age = 50;
if ($age < 30)
{
echo "Your age is less than 30!";
}
else
{
echo "Your age is greater than or equal to 30!";
}
PHP IF ELSEIF STATEMENT

If you've got more than two choices to choose from, you can use
the elseif statement.
<?php
$age = 50;
if ($age < 30)
{echo "Your age is less than
30!";}
elseif ($age > 30 && $age < 40)
{echo "Your age is between 30
and 40!";}
elseif ($age > 40 && $age < 50)
{echo "Your age is between 40
and 50!";}
else
{echo "Your age is greater than
50!";}
?>
LOOPS IN PHP

• Loops in PHP are useful when you want to execute;


• A piece of code repeatedly until a condition evaluates false.
• Code is executed repeatedly as long as a condition evaluates to true, and
as soon as the condition evaluates to false, the script continues executing
the code after the loop.
WHILE LOOP IN PHP

• The while loop is used when you want to execute a piece of code repeatedly
while the condition is true. It will stop when the condition evaluates to false.

<?php
$x = 1;
while($x <= 5)
{ echo "The number is: $x <br>";
$x=$x+1;}
// $x=$x+1 also can be written like $x++
?>
EXAMPLE
<?php
$x = 1;
while($x <= 5)
{ echo "The number is: $x <br>";
$x=$x+1;}
// $x=$x+1 also can be written like $x++
?>
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
DO-WHILE LOOP IN PHP

• The do-while loop is very similar to the while loop, with the only difference being
that the while condition is checked at the end of the first iteration.
• Thus, we can guarantee that the loop code is executed at least once, irrespective of
the result of the while expression.
EXAMPLE

<?php
$x = 1;
do {
echo "I like ICT <br>";
$x++;
} while ($x <= 5);
?>
//X = x+1 also (x++)
EXAMPLE 2

<?php
$x = 6;
do {
echo "I like ICT <br>";
$x++;
} while ($x <= 5);
?>
FOR LOOP IN PHP
• Generally, the for loop is used to execute a piece of code a specific number of times.
• In other words, if you already know the number of times you want to execute a block of
code, it's the for loop which is the best choice.

for (init counter; test counter; increment counter)


{
code to be executed for each iteration;
}
Parameters:
• init counter: Initialize the loop counter value
• test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
• increment counter: Increases the loop counter value
EXAMPLE
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The number is: 0
.
.
.
The number is: 10

• Example Explained
• $x = 0; - Initialize the loop counter ($x), and set the start value to 0
• $x <= 10; - Continue the loop as long as $x is less than or equal to 10
EXAMPLE

<?php
for ($x = 0; $x <= 100; $x+=10) {
echo "The number is: $x <br>";
}
?>
ANSWER
The number is: 0
The number is: 10
The number is: 20
The number is: 30
The number is: 40
The number is: 50
The number is: 60
The number is: 70
The number is: 80
The number is: 90
The number is: 100
CONCATENATION

• There are string (String is a sequence of characters, like "Nice day") operators provided by
PHP.
• Concatenation Operator ("."):
This operator combines two string values and returns it as a new string.
<?php
//concatenate text
$text1="Dear Students";
$text2="Nice Day";

. .
echo $text1 "," $text2;
?>
Output
Dear Students,Nice Day
Concatenate string with comma(,)
• We can use Comma as a concatenation operator in php to multiple
parameters

Example :
echo 'Multiple Parameter ', 'Example With ', ' echo.’;

Output:
Multiple Parameter Example With echo.
PHP DATA TYPES

• 1. String
• 2. Integer
• 3. Float
• 4. Boolean
• 5. Array
01) PHP STRING

• String is a sequence of characters, like "Nice day".

• There are two string operators provided by PHP.


1.Concatenation Operator ("."):
This operator combines two string values and returns it as a new string.
2.Concatenating Assignment operator (".="):
This operation attaches the argument on the right side to the argument on the left side.

PHP String Functions.


• str_word_count() - Count words in a string
• strlen() - Return the length of a string
• strrev() - Reverse a string
• str_replace() - Replace text within a string
<?php
//concatenate text
$text1="Dear Students";
$text2="Nice Day";

. .
echo $text1 ", " $text2;
echo "<br/>";

Output //word count...

.
echo "No of words =" str_word_count($text2);
echo "<br/>";
//Character length
echo "No of characters in '$text2'
.
=" strlen($text2);
echo "<br/>";
//Reverse Order
echo strrev($text2);
echo "<br/>";
//Word replace
echo str_replace("Nice", "Good", $text2);
PHP INTEGER
• An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647

• Rules for integers:

• An integer must have at least one digit.


• An integer must not have a decimal point.
• An integer can be either positive or negative.
• Integers can be specified in, decimal, hexadecimal, octal or binary notation.
<?php
$up=60;
$qty=100; Output
$value=$up*$qty;
echo "Value is " . $value;
?>
03) PHP FLOAT
A float (floating point number) is a number with a decimal point or a number in exponential
form.

Ex: 1.2
83.4
32
04) PHP BOOLEAN

A Boolean represents two possible states: TRUE or FALSE.


05) PHP ARRAYS

• An array stores multiple values in one single variable.

• In the following example $weekdays is an array.

• The PHP var_dump() function returns the data type and value:

Syntax:
array();
Ex:
<?php
$weekdays = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturdey");
var_dump($weekdays);
?> OUTPUT

array(7) {
[0]=> string(6) "Sunday"
[1]=> string(6) "Monday"
[2]=> string(7) "Tuesday"
[3]=> string(9) "Wednesday"
[4]=> string(8) "Thursday"
[5]=> string(6) "Friday"
[6]=> string(8) "Saturday" }
EXERCISE
Ex03: Ex06: <?php
<?php $x = 5;
Ex01 $txt = “ICT"; $y = 4;
echo "I love $txt!"; echo $x + $y;
<?php ?> ?>
echo "Welcome ";
echo "ICT Students"; Ex07
Ex04: <?php
echo "<br/> This is a PHP text.";
<?php $x = 5;
?> $txt = “ICT”; $y = 4;
echo "I love " . $txt . "!"; $tot = $x+$y;
?> echo "Total is ", $tot;
Ex02:
?>
<?php Ex05:
$text="Nice Day"; <?php Ex08
$txt = “ICT"; <?php
$x=200;
echo "I love "."<br/>" . $txt . "!"; $x=10/*+30*/+5;
$y = 10.5; ?> echo 'Answer is '.$x;
?> ?>
SAVING PHP FILES…

• Open a simple text editor like Notepad / Notepad++


• Write the code.
• Save the file as NameOfTheFile.php
• (Location C:\xampp\htdocs\Phpex01.php)
• (Save as type -> All Files) (Encoding -> UTF-8)
PHP CASE SENSITIVITY

• In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-
defined functions are not case-sensitive.
• In the example below, all three echo statements below are equal and legal:

Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Note: However; all variable names are case-sensitive!

Look at the example below;


The first statement will display the value of red as the $color variable!
This is because $color, $COLOR, and $coLOR are treated as three different variables:

Example
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
$COLOR = “blue”;
$coLOR = “white”;

echo "My car is " . $color . "<br>";


echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
PHP COMMENTS
// Single line comment here…

/* Multiple line
comment here…
*/

<?php
$x=10/*+30*/+5; //middle of the line comment
echo 'Answer is '.$x;
?>
PHP FUNCTIONS
• The real power of PHP comes from its functions.
• PHP has more than 1000 built-in functions, and in addition you can create your own custom
functions.

PHP Built-in Functions


• PHP has over 1000 built-in functions that can be called directly, from within a script, to
perform a specific task.

PHP User Defined Functions


• Besides the built-in PHP functions, it is possible to create your own functions.
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.
CREATE A USER DEFINED FUNCTION IN PHP

A user-defined function declaration starts with the word function:

Note that while creating a function its name should start with keyword function and all
the PHP code should be put inside { and } braces as shown in the following example
below −

Syntax
function functionName() {
code to be executed;
}

Note: A function name must start with a letter or an underscore.


Function names are NOT case-sensitive.
EXAMPLE 1

<?php

function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function

?>
EXAMPLE 2

<?php

/* Defining a PHP Function */


function greetingMessage() {

echo "You are really a nice person, Have a nice


time!";
}

/* Calling a PHP Function */


greetingMessage();

?>
BUILT-IN FUNCTIONS

• chr() Returns a character from a specified ASCII value

Example :-

<?php
echo chr(52) . "<br>"; // Decimal value
echo chr(052) . "<br>"; // Octal value
echo chr(0x52) . "<br>"; // Hex value
?>
BUILT-IN FUNCTIONS

• echo() Outputs one or more strings

Example :- Write some text to the output

<?php
echo "Hello world!";
?>
BUILT-IN FUNCTIONS

• trim() Removes whitespace or other characters from both sides of a string

Example :- Remove characters from both sides of a string ("He" in "Hello" and "d!" in "World"):

<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
BUILT-IN FUNCTIONS

• getFile() Returns the full path of the file in which the exception was thrown

Example :- Throw an exception and output the path of the file in which the exception occurred:

<?php
try {
throw new Exception("An error occurred");
} catch(Exception $e) {
echo "Error in this file: " . $e->getFile();
}
?>
BUILT-IN FUNCTIONS

• array() Creates an array

Example :- Create an indexed array named $cars, assign three elements to it, and then print a text
containing the array values:

<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
PHP MYSQL DATABASE

• With PHP, you can connect to and manipulate databases.


• MySQL is the most popular database system used with PHP.
WHAT IS MYSQL?

• MySQL is a database system used on the web


• MySQL is a database system that runs on a server
• MySQL is ideal for both small and large applications
• MySQL is very fast, reliable, and easy to use
• MySQL uses standard SQL
• MySQL compiles on a number of platforms
• The data in a MySQL database are stored in tables. A table is a
collection of related data, and it consists of columns and rows.
• Databases are useful for storing information categorically. A company
may have a database with the following tables:

• Employees
• Products
• Customers
• Orders
PHP + MYSQL DATABASE SYSTEM
PHP combined with MySQL are cross-platform

Database Queries
• A query is a question or a request.
• We can query a database for specific information and have a
recordset returned.
• Look at the following query (using standard SQL):
SELECT LastName FROM Employees
• The query above selects all the data in the "LastName" column
from the "Employees" table.
OPEN A CONNECTION TO MYSQL
• Before we can access data in the MySQL database, we need to be able to connect to
the server:
Example
• <?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
CLOSE THE CONNECTION

• The connection will be closed automatically when the script ends. To


close the connection before, use the following:

• $conn->close();
A database consists of one or more tables.

You will need special CREATE privileges to create or to delete a MySQL database.

Create a MySQL Database Using MySQLi

The CREATE DATABASE statement is used to create a database in MySQL.

The following examples create a database named "myDB":


<?php
$servername = "localhost";
$username = "username";
$password = "password";
EXAMPLE
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>
CREATE A MYSQL TABLE USING
MYSQLI
• The CREATE TABLE statement is used to create a table in MySQL.
• We will create a table named "MyGuests", with five columns: "id",
"firstname", "lastname", "email“.

CREATE TABLE MyGuests (


id INT(6) PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),)
THE FOLLOWING EXAMPLES SHOWS HOW TO CREATE THE TABLE IN PHP:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
// sql to create table
$sql = ”CREATE TABLE MyGuests (
id INT(6) PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50))”;
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;}
INSERT DATA INTO MYSQL
• After a database and a table have been created, we can start adding data in them.
• Here are some syntax rules to follow:
• The SQL query must be quoted in PHP
• String values inside the SQL query must be quoted
• Numeric values must not be quoted
• The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
EXAMPLE
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
//insert data into table
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";}
else {
echo "Error: " . $sql . "<br>" . $conn->error;}
$conn->close();
?>
SELECT DATA WITH MYSQLI

THE FOLLOWING EXAMPLE SELECTS THE ID, FIRSTNAME AND LASTNAME COLUMNS FROM THE MYGUESTS
TABLE AND DISPLAYS IT ON THE PAGE:
<?php
$servername = "localhost";
$username = "username"; id firstyname lastname
$password = "password"; 1 John Doe
$dbname = "myDB"; 2 Mary Moe
// Create connection
3 Julie Dooley
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";} }
else {
echo "0 results";}
$conn->close();
First, we set up an SQL query that selects the id, firstname and
lastname columns from the MyGuests table.
The next line of code runs the query and puts the resulting data
into a variable called $result.
Then, the function num_rows() checks if there are more than
zero rows returned.
If there are more than zero rows returned, the function
fetch_assoc() puts all the results into an associative array that
we can loop through. (dictinaray that can hold data (key,value))
The while() loop loops through the result set and outputs the
data from the id, firstname and lastname columns
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {

// output data of each row


while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";} }
else {
echo "0 results";}

id: 1 - Name: John Doe


id: 2 - Name: Mary Moe
id: 3 - Name: Julie Dooley

You might also like