SlideShare a Scribd company logo
PHP
Select Data From a MySQL Database<?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 = "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();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
PHP Delete Data From MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
PHP Update Data in MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
PHP - Validate Name
using RE
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
The preg_match() function searches a string for pattern, returning true if the
pattern exists, and false otherwise.
PHP - Keep The Values in The Form
Name: <input type="text" name="name" value="<?php echo $name;?>">
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
Website: <input type="text" name="website" value="<?php echo $website;?>">
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="other") echo "checked";?>
value="other">Other
PHP 5 File Handling
<?php
echo readfile("webdictionary.txt");
?>
The PHP code to read the file and write it to the output buffer is as
follows (the readfile() function returns the number of bytes read on
success
PHP Open File - fopen()
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
The first parameter of fread() contains the name of the file to read from
and the second parameter specifies the maximum number of bytes to
read.
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer
starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file.
Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer
starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file.
Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
PHP 5 File Create/Write
$myfile = fopen("testfile.txt", "w")
The fopen() function is also used to create a file. Maybe a little
confusing, but in PHP, a file is created using the same function used to
open files.
If you use fopen() on a file that does not exist, it will create it, given
that the file is opened for writing (w) or appending (a).
PHP Write to File - fwrite()
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doen";
fwrite($myfile, $txt);
$txt = "Jane Doen";
fwrite($myfile, $txt);
fclose($myfile);
?>
PHP 5 Cookies
A cookie is often used to identify a user. A cookie is a small file that the
server embeds on the user's computer. Each time the same computer
requests a page with a browser, it will send the cookie too. With PHP,
you can both create and retrieve cookie values.
PHP Create/Retrieve a Cookie
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
creates a cookie named "user" with the
value "John Doe". The cookie will
expire after 30 days (86400 * 30). The
"/" means that the cookie is available in
entire website (otherwise, select the
directory you prefer).
Delete a Cookie
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
What is a PHP Session?
When you work with an application, you open it, do some changes, and then
you close it. This is much like a Session. The computer knows who you are. It
knows when you start the application and when you end. But on the internet
there is one problem: the web server does not know who you are or what
you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used
across multiple pages (e.g. username, favorite color, etc). By default, session
variables last until the user closes the browser.
So; Session variables hold information about one single user, and are
available to all pages in one application.
Start a PHP Session
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Get PHP Session Variable Values
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Destroy a PHP Session
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
PHP Exception Handling
Exception handling is used to change the normal flow of
the code execution if a specified error (exceptional)
condition occurs. This condition is called an exception.
This is what normally happens when an exception is
triggered:
• The current code state is saved
• The code execution will switch to a predefined (custom)
exception handler function
• Depending on the situation, the handler may then
resume the execution from the saved code state,
terminate the script execution or continue the script
from a different location in the code
Try, throw and catch
To avoid the error from the example above, we need to create the proper
code to handle an exception.
Proper exception code should include:
• try - A function using an exception should be in a "try" block. If the
exception does not trigger, the code will continue as normal. However if
the exception triggers, an exception is "thrown"
• throw - This is how you trigger an exception. Each "throw" must have at
least one "catch“
• catch - A "catch" block retrieves an exception and creates an object
containing the exception information
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or
below");
}
return true;
}
//trigger exception in a "try" block
try {
checkNum(2);
//If the exception is thrown, this text will not be
shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>
The checkNum() function is created. It checks if a number is
greater than 1. If it is, an exception is thrown
The checkNum() function is called in a "try" block
The exception within the checkNum() function is thrown
The "catch" block retrieves the exception and creates an object
($e) containing the exception information
The error message from the exception is echoed by calling $e-
>getMessage() from the exception object

More Related Content

PDF
Web Development Course: PHP lecture 3
PDF
Rooted 2010 ppp
PDF
Introduction to ReasonML
PDF
Web Development Course: PHP lecture 1
KEY
Php 101: PDO
PPT
Quebec pdo
PDF
Perkenalan ReasonML
PPT
Intro to php
Web Development Course: PHP lecture 3
Rooted 2010 ppp
Introduction to ReasonML
Web Development Course: PHP lecture 1
Php 101: PDO
Quebec pdo
Perkenalan ReasonML
Intro to php

What's hot (20)

PDF
Web Development Course: PHP lecture 4
TXT
My shell
PPT
Php Crash Course
TXT
PPT
Php mysql
PDF
Pemrograman Web 9 - Input Form DB dan Session
PDF
Xlab #1: Advantages of functional programming in Java 8
ODP
The promise of asynchronous php
KEY
PDF
PHP Object Injection Vulnerability in WordPress: an Analysis
PDF
Solr Anti-Patterns: Presented by Rafał Kuć, Sematext
PDF
PHPCon 2016: PHP7 by Witek Adamus / XSolve
ODP
My app is secure... I think
ODP
My app is secure... I think
PDF
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
PPTX
Phphacku iitd
PPT
Class 6 - PHP Web Programming
PPTX
Flask restfulservices
PDF
Solr & Lucene @ Etsy by Gregg Donovan
PPTX
Electrify your code with PHP Generators
Web Development Course: PHP lecture 4
My shell
Php Crash Course
Php mysql
Pemrograman Web 9 - Input Form DB dan Session
Xlab #1: Advantages of functional programming in Java 8
The promise of asynchronous php
PHP Object Injection Vulnerability in WordPress: an Analysis
Solr Anti-Patterns: Presented by Rafał Kuć, Sematext
PHPCon 2016: PHP7 by Witek Adamus / XSolve
My app is secure... I think
My app is secure... I think
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Phphacku iitd
Class 6 - PHP Web Programming
Flask restfulservices
Solr & Lucene @ Etsy by Gregg Donovan
Electrify your code with PHP Generators
Ad

Similar to php part 2 (20)

PDF
&lt;img src="../i/r_14.png" />
PDF
php-mysql-tutorial-part-3
PDF
php-mysql-tutorial-part-3
PDF
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
PPTX
Quick beginner to Lower-Advanced guide/tutorial in PHP
PPSX
Php session
PDF
Web 8 | Introduction to PHP
PPTX
PPTX
advancing in php programming part four.pptx
PPTX
Php with mysql ppt
PDF
Php a dynamic web scripting language
PPT
PHP variables
PPT
Php basic for vit university
PPSX
Php and MySQL
PPTX
HackU PHP and Node.js
PPT
PHP Workshop Notes
PDF
PPTX
Unit-1 PHP Basic1 of the understanding of php.pptx
PPTX
PHP PPT FILE
&lt;img src="../i/r_14.png" />
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
Quick beginner to Lower-Advanced guide/tutorial in PHP
Php session
Web 8 | Introduction to PHP
advancing in php programming part four.pptx
Php with mysql ppt
Php a dynamic web scripting language
PHP variables
Php basic for vit university
Php and MySQL
HackU PHP and Node.js
PHP Workshop Notes
Unit-1 PHP Basic1 of the understanding of php.pptx
PHP PPT FILE
Ad

Recently uploaded (20)

PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Lesson notes of climatology university.
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Sports Quiz easy sports quiz sports quiz
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
master seminar digital applications in india
PDF
Complications of Minimal Access Surgery at WLH
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
Anesthesia in Laparoscopic Surgery in India
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Lesson notes of climatology university.
O7-L3 Supply Chain Operations - ICLT Program
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Sports Quiz easy sports quiz sports quiz
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Microbial diseases, their pathogenesis and prophylaxis
Microbial disease of the cardiovascular and lymphatic systems
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Abdominal Access Techniques with Prof. Dr. R K Mishra
Supply Chain Operations Speaking Notes -ICLT Program
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
master seminar digital applications in india
Complications of Minimal Access Surgery at WLH
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Basic Mud Logging Guide for educational purpose
Module 4: Burden of Disease Tutorial Slides S2 2025

php part 2

  • 1. PHP
  • 2. Select Data From a MySQL Database<?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 = "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(); ?>
  • 3. <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 results"; } mysqli_close($conn); ?>
  • 4. PHP Delete Data From MySQL <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // sql to delete a record $sql = "DELETE FROM MyGuests WHERE id=3"; if (mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); } mysqli_close($conn); ?>
  • 5. PHP Update Data in MySQL <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if (mysqli_query($conn, $sql)) { echo "Record updated successfully"; } else { echo "Error updating record: " . mysqli_error($conn); } mysqli_close($conn); ?>
  • 6. PHP - Validate Name using RE $name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.
  • 7. PHP - Keep The Values in The Form Name: <input type="text" name="name" value="<?php echo $name;?>"> E-mail: <input type="text" name="email" value="<?php echo $email;?>"> Website: <input type="text" name="website" value="<?php echo $website;?>"> Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea> Gender: <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male <input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
  • 8. PHP 5 File Handling <?php echo readfile("webdictionary.txt"); ?> The PHP code to read the file and write it to the output buffer is as follows (the readfile() function returns the number of bytes read on success
  • 9. PHP Open File - fopen() <?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("webdictionary.txt")); fclose($myfile); ?> The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.
  • 10. Modes Description r Open a file for read only. File pointer starts at the beginning of the file w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist x Creates a new file for write only. Returns FALSE and an error if file already exists r+ Open a file for read/write. File pointer starts at the beginning of the file w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
  • 11. PHP 5 File Create/Write $myfile = fopen("testfile.txt", "w") The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).
  • 12. PHP Write to File - fwrite() <?php $myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); $txt = "John Doen"; fwrite($myfile, $txt); $txt = "Jane Doen"; fwrite($myfile, $txt); fclose($myfile); ?>
  • 13. PHP 5 Cookies A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
  • 14. PHP Create/Retrieve a Cookie <?php $cookie_name = "user"; $cookie_value = "John Doe"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day ?> <html> <body> <?php if(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' is not set!"; } else { echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Value is: " . $_COOKIE[$cookie_name]; } ?> </body> </html> creates a cookie named "user" with the value "John Doe". The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer).
  • 15. Delete a Cookie <?php // set the expiration date to one hour ago setcookie("user", "", time() - 3600); ?> <html> <body> <?php echo "Cookie 'user' is deleted."; ?> </body> </html>
  • 16. What is a PHP Session? When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state. Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser. So; Session variables hold information about one single user, and are available to all pages in one application.
  • 17. Start a PHP Session <?php // Start the session session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Set session variables $_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat"; echo "Session variables are set."; ?> </body> </html>
  • 18. Get PHP Session Variable Values <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Echo session variables that were set on previous page echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>"; echo "Favorite animal is " . $_SESSION["favanimal"] . "."; ?> </body> </html>
  • 19. Destroy a PHP Session <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // remove all session variables session_unset(); // destroy the session session_destroy(); ?> </body> </html>
  • 20. PHP Exception Handling Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception. This is what normally happens when an exception is triggered: • The current code state is saved • The code execution will switch to a predefined (custom) exception handler function • Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code
  • 21. Try, throw and catch To avoid the error from the example above, we need to create the proper code to handle an exception. Proper exception code should include: • try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown" • throw - This is how you trigger an exception. Each "throw" must have at least one "catch“ • catch - A "catch" block retrieves an exception and creates an object containing the exception information
  • 22. <?php //create function with an exception function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception in a "try" block try { checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below'; } //catch exception catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } ?> The checkNum() function is created. It checks if a number is greater than 1. If it is, an exception is thrown The checkNum() function is called in a "try" block The exception within the checkNum() function is thrown The "catch" block retrieves the exception and creates an object ($e) containing the exception information The error message from the exception is echoed by calling $e- >getMessage() from the exception object