SlideShare a Scribd company logo
1 of 31
Accessing MySQL with
PHP
Overview of My SQL Structure and
Syntax
Databases are stores of information.
MySQL is an open-source database that can be used for web
applications.
The only requirement is that, you need to have a server at your
disposal where you can install MySQL.
Types of Storage Engines
◦ MyISAM (Indexed Sequential Access Method)
◦ MERGE
◦ MEMORY
◦ InnoDB
◦ BDB (BerkeleyDB )
My SQL Syntax and
Commands
Common commands
◦ CREATE : Creates new databases and tables
◦ ALTER : Modifies existing tables
◦ SELECT : Chooses the data you want
◦ DELETE : Erases the data from your table
◦ DESCRIBE : Lets you know the structure and
specifics of the table
◦ INSERT INTO table name VALUES : Puts values
into the table
◦ UPDATE : Lets you modify data already in a table
◦ DROP : Deletes an entire table or database
Data Type in
MySQL Text Types
◦ char(size)
It is used to store no. of character and it is in fixed length.
◦ varchar(size)
It is used to store alphanumeric data of variable length.
◦ blob
It is binary large object which can hold variable amount of business data
◦ Binary and Varbinary
These 2 type are similar to char and varchar except that they hold
binary string rather than ascii string
 Number Types
◦ int(size)
It is used to store integer type of data.
It divide in to 5 segment int, tiny int, small int, medium int,big int
◦ Float(size,precision)
It is allow to store decimal numbers with specific precision.
◦ Double(size,precision)
It is allow to store large floating decmial point value.
Date
◦ Hold the date value
◦ Range between 1000-01-01 to 9999-12-31
Time
◦ Hold the time value
◦ Standard format hh:mm:ss
Datetime
◦ It hold date and time value
◦ Range between 1000-01-01 00:00:00 to 9999-12-31 23:59:59
◦ Standard format yyyy-mm-dd hh:mm:ss
year
◦ It is required 1 byte for holds year value
How PHP Fits with My
SQLYou can use MySQL commands within PHP code.
Some of the more commonly used functions are:
◦ mysql_connect($host, $username, $password) : Connects to the
MySQL server and returns a resource which is used to reference the
connection.
◦ Mysql_pconnect():-
◦ mysql_select_db($database, $resource) : Equivalent to the MySQL
command USE and sets the active database.
◦ mysql_query($query, $resource) : Used to send any MySQL
command to the database server. In the case of SELECT queries, a
reference to the result set will be returned.
◦ mysql_fetch_array($result) : Return a row of data from the query ’
s result set as an associative array, numeric array or both.
◦ mysql_fetch_assoc($result) : Return a row of data from the query ’
s result set as an associative array.
◦ mysql_error([$resource]) : Shows the error message generated by
the previous query.
◦ die(<String> $msg)
die() prints message and exits the current script.
Cont…
To connect with database
◦ $con = mysql_connect ($host, $username, $password)
$host = ‘localhost’;
$user = ‘root’;
$pass = ‘’;
$con = mysql_connect($host, $user, $pass);
The following statement has the same effect:
$con = mysql_connect(‘localhost’, ‘root’, ‘’);
To close the connection
◦ mysql_close($con);
To select database
$db = mysql_select_db(DBName,$con)
Create
Table
Syntax:-
◦ CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
Example:-
◦ CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)
Important: A database must be selected before a table can be
created. The database is selected with the mysql_select_db()
function.
Insert data into tables
The INSERT INTO statement is used to add new records to a database table.
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be
inserted, only their values:
INSERT INTO table_name VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be
inserted:
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1,
value2, value3,...)
To get PHP to execute the statements above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example:-
// insert data into table
$insert=mysql_query("INSERT INTO Persons VALUES (1, 'Glenn',
'Quagmire',33 )");
// Execute query
mysql_query($insert,$con);
// insert data into table
$insert=mysql_query("INSERT INTO Persons (personID,FirstName,
LastName, Age) VALUES (2,'Peter', 'Griffin',35)");
Insert data into table using
FORM<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text"
name="firstname">
Lastname: <input type="text"
name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
When a user clicks the submit button in the HTML
form in the example above, the form data is sent to
"insert.php".
Here is the "insert.php" page:
<?php
$con = mysql_connect('localhost', 'root', '') or
die ('Unable to connect. Check your connection
parameters.');
echo "Connection successfullyn";
// select database
mysql_select_db('student', $con) or die(mysql_error($con));
echo "Database activen";
//insert data
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
Retrieve the Data From a Database
Table$result = mysql_query("select * from Persons ")
To retrive the data from the table we are using the
mysql_fetch_array() function.
When we pass $result into the mysql_fetch_array function --
mysql_fetch_array($result) -- an associative array (firstname,
lastname, age) is returned.
mysql_fetch_array() function to return the first row from the
recordset as an array.
In our MySQL table " Persons," there are only three fields that we
care about: firstname, lastname and age.
These names are the keys to extracting the data from our
associative array.
To get the firstname we use $row[‘firstname'] , to get the
lastname we use $row[‘lastnamr'] and to get the age we
use $row['age'].
fetch array while
loopEach call to mysql_fetch_array() returns the next row
in the recordset.
$result = mysql_query("SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " .
$row['LastName'].””.$row[‘age’];
echo "<br />";
}
The while loop loops through all the records in the
recordset.
To print the value of each row, we use the PHP $row
variable ($row['FirstName']
,$row['LastName'],$row[‘age’]).
Retrieving data
To retrieving the data from database 2 function are used.
◦ mysql_fetch_array()
◦ mysql_fetch_assoc()
The mysql_fetch_assoc() function returns a single row from the table
as an associative array. The data can be retrieved by using the column
names as indexes.
The mysql_fetch_array() function returns a single row from the table.
The data can be retrieved by column names and column indexes.
@ is used to generate user defined exception other than System
generated errors.
mysql_num_fields( $result ) is used to count total number of fields and
coloumn from your database.
$num_cols = mysql_num_fields( $result );
mysql_num_rows( $result ) is used to count total number of recods
from your database.
$num_rows = mysql_num_rows( $result );
Include() AND include_once()
Include() AND require():-
◦ The include and require statements are used to insert useful
codes written in other files, in the flow of execution.
◦ Include and require are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will
continue
So, if you want the execution to go on and show users the output, even if
the include file is missing, use include(). Otherwise, require().
◦ Syntax:-
Include(“file name with path”); or include “file name with path”;
Require(“file name with path”); or require “file name with path”;
◦ Example:-
<html>
<body>
<?php include 'header.php'; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
Include_once() AND
require_once()
Include_once() & require_once() both are functioning same as
include() and require.
But the main difference between those function is include_once()
and require_once() include file only once while include() and
require() include files as many time as you want.
◦ Syntax:-
Include_once(“file name with path”); or include_once “file name with path”;
Require_once(“file name with path”); or require_once “file name with path”;
◦ Example:-
<html>
<body>
<?php include_once 'header.php'; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
Maintaining State in PHP using Cookies &
Sessions
Why to maintain state in php?
◦ HTTP is stateless Protocol.
◦ Any data you have stored is forgotten about
when the page has been sent to the client
and the connection is closed.
◦ Cookie is tiny bits of information that a web
site could store on the client's machine that
were sent back to the web site each time a
new page was requested. Each cookie could
only be read by the web site that had written
it.
What is a Cookie?
A cookie is a small text file that is
stored on a user’s computer.
Each cookie on the user’s computer is
connected to a particular domain.
Each cookie be used to store up to
4kB of data.
A maximum of 20 cookies can be
stored on a user’s PC per domain.
1. User sends a request for page at
www.example.com for the first time.
Exampl
e
page request
2. Server sends back the page xhtml to
the browser AND stores some data in
a cookie on the user’s PC.
Exampl
e
cookie data
xhtml
3. At the next page request for domain
www.example.com, all cookie data
associated with this domain is sent
too.
Exampl
e
page request
cookie data
setcookie(name [,value [,expire [,path [,domain
[,secure]]]]])
name = cookie name
value = data to store (string)
expire = UNIX timestamp when the cookie expires.
Default is that cookie expires when browser is closed.
path = Path on the server within and below which the
cookie is available on.
domain = Domain at which the cookie is available for.
secure = If cookie should be sent over HTTPS
connection only. Default false.
Set a
cookie
setcookie(‘name’,’Robert’)
This command will set the cookie called name on
the user’s PC containing the data Robert. It will be
available to all pages in the same directory or
subdirectory of the page that set it (the default path
and domain). It will expire and be deleted when the
browser is closed (default expire).
setcookie(‘age’,’20’,time()+60*60*24*30)
This command will set the cookie called age on
the user’s PC containing the data 20. It will be available
to all pages in the same directory or subdirectory of the
page that set it (the default path and domain). It will
expire and be deleted after 30 days.
Set a cookie -
examples
As the setcookie command involves
sending a HTTP header request, it must
be executed before any xhtml is
echoed to the browser, including
whitespace.
Where to write code for Cookie…
correct!
incorrect.
echoed
whitespace
before
setcookie
All cookie data is available through the
superglobal $_COOKIE:
$variable = $_COOKIE[‘cookie_name’]
or
$variable = $HTTP_COOKIE_VARS[‘cookie_name’];
e.g.
$age = $_COOKIE[‘age’]
Read cookie
data
To remove a cookie, simply overwrite the
cookie with a new one with an expiry time
in the past…
setcookie(‘cookie_name’,’’,time()-
6000)
Delete a
cookie
You can store user information (e.g. username,
items selected, etc.) in the server side for later
use using PHP session.
Sessions work by creating a unique id (UID) for
each visitor and storing variables based on this
UID.
The UID is either stored in a cookie or is
propagated in the URL.
PHP
Sessions
<?php session_start(); ?>
<html>
<body>
</body>
</html>
session_start() function must appear BEFORE the <html>
tag.
Before you can store user information in your PHP
session, you must first start up the session.
PHP
Sessions Starting a PHP session:
<?php
session_start();
?>
• This tells PHP that a session is requested.
• A session ID is then allocated at the server
end.
• session ID looks like:
sess_f1234781237468123768asjkhfa78912
34g
 $_SESSION
 e.g., $_SESSION[“intVar”] = 10;
 Testing if a session variable has been
set:
session_start();
if(!$_SESSION['intVar']) {...} //intVar is set or not
Session
variables
Session
Example 1<?php
session_start();
if (!isset($_SESSION["intVar"]) ){
$_SESSION["intVar"] = 1;
} else {
$_SESSION["intVar"]++;
}
echo "<p>In this session you have accessed this
page " . $_SESSION["intVar"] . "times.</p>";
?>
Ending
sessionsunset($_SESSION[‘name’])
–Remove a session variable
session_destroy()
– Destroys all data registered to a session
– does not unset session global variables and cookies
associated with the session
–Not normally done - leave to timeout

More Related Content

What's hot

Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database JonesJohn David Duncan
 
Scaling Databases with DBIx::Router
Scaling Databases with DBIx::RouterScaling Databases with DBIx::Router
Scaling Databases with DBIx::RouterPerrin Harkins
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHPmarkstory
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xqueryAmol Pujari
 
BITS: Introduction to relational databases and MySQL - SQL
BITS: Introduction to relational databases and MySQL - SQLBITS: Introduction to relational databases and MySQL - SQL
BITS: Introduction to relational databases and MySQL - SQLBITS
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3markstory
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sqlsalissal
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Rebecca Grenier
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersPostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersAmanda Gilmore
 

What's hot (18)

Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Scaling Databases with DBIx::Router
Scaling Databases with DBIx::RouterScaling Databases with DBIx::Router
Scaling Databases with DBIx::Router
 
DB2 Native XML
DB2 Native XMLDB2 Native XML
DB2 Native XML
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
 
MYSQL
MYSQLMYSQL
MYSQL
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xquery
 
BITS: Introduction to relational databases and MySQL - SQL
BITS: Introduction to relational databases and MySQL - SQLBITS: Introduction to relational databases and MySQL - SQL
BITS: Introduction to relational databases and MySQL - SQL
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
 
Persistences
PersistencesPersistences
Persistences
 
Mysql Ppt
Mysql PptMysql Ppt
Mysql Ppt
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
 
veracruz
veracruzveracruz
veracruz
 
PostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL SuperpowersPostgreSQL's Secret NoSQL Superpowers
PostgreSQL's Secret NoSQL Superpowers
 
My sql tutorial-oscon-2012
My sql tutorial-oscon-2012My sql tutorial-oscon-2012
My sql tutorial-oscon-2012
 

Similar to Learn PHP Lacture2

PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part IIFirdaus Adib
 
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxModule 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxmoirarandell
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sqlsaritasingh19866
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptxnatesanp1234
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDhivyaa C.R
 
Web app development_crud_13
Web app development_crud_13Web app development_crud_13
Web app development_crud_13Hassen Poreya
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPVineet Kumar Saini
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2Neeraj Mathur
 

Similar to Learn PHP Lacture2 (20)

PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
Php summary
Php summaryPhp summary
Php summary
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part II
 
Introduction to php database connectivity
Introduction to php  database connectivityIntroduction to php  database connectivity
Introduction to php database connectivity
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxModule 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
 
PHP and Mysql
PHP and MysqlPHP and Mysql
PHP and Mysql
 
Php verses my sql
Php verses my sqlPhp verses my sql
Php verses my sql
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sql
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptx
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
 
PHP with MYSQL
PHP with MYSQLPHP with MYSQL
PHP with MYSQL
 
Web app development_crud_13
Web app development_crud_13Web app development_crud_13
Web app development_crud_13
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
 

Recently uploaded

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 

Recently uploaded (20)

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 

Learn PHP Lacture2

  • 2. Overview of My SQL Structure and Syntax Databases are stores of information. MySQL is an open-source database that can be used for web applications. The only requirement is that, you need to have a server at your disposal where you can install MySQL. Types of Storage Engines ◦ MyISAM (Indexed Sequential Access Method) ◦ MERGE ◦ MEMORY ◦ InnoDB ◦ BDB (BerkeleyDB )
  • 3. My SQL Syntax and Commands Common commands ◦ CREATE : Creates new databases and tables ◦ ALTER : Modifies existing tables ◦ SELECT : Chooses the data you want ◦ DELETE : Erases the data from your table ◦ DESCRIBE : Lets you know the structure and specifics of the table ◦ INSERT INTO table name VALUES : Puts values into the table ◦ UPDATE : Lets you modify data already in a table ◦ DROP : Deletes an entire table or database
  • 4. Data Type in MySQL Text Types ◦ char(size) It is used to store no. of character and it is in fixed length. ◦ varchar(size) It is used to store alphanumeric data of variable length. ◦ blob It is binary large object which can hold variable amount of business data ◦ Binary and Varbinary These 2 type are similar to char and varchar except that they hold binary string rather than ascii string  Number Types ◦ int(size) It is used to store integer type of data. It divide in to 5 segment int, tiny int, small int, medium int,big int ◦ Float(size,precision) It is allow to store decimal numbers with specific precision. ◦ Double(size,precision) It is allow to store large floating decmial point value.
  • 5. Date ◦ Hold the date value ◦ Range between 1000-01-01 to 9999-12-31 Time ◦ Hold the time value ◦ Standard format hh:mm:ss Datetime ◦ It hold date and time value ◦ Range between 1000-01-01 00:00:00 to 9999-12-31 23:59:59 ◦ Standard format yyyy-mm-dd hh:mm:ss year ◦ It is required 1 byte for holds year value
  • 6. How PHP Fits with My SQLYou can use MySQL commands within PHP code. Some of the more commonly used functions are: ◦ mysql_connect($host, $username, $password) : Connects to the MySQL server and returns a resource which is used to reference the connection. ◦ Mysql_pconnect():- ◦ mysql_select_db($database, $resource) : Equivalent to the MySQL command USE and sets the active database. ◦ mysql_query($query, $resource) : Used to send any MySQL command to the database server. In the case of SELECT queries, a reference to the result set will be returned. ◦ mysql_fetch_array($result) : Return a row of data from the query ’ s result set as an associative array, numeric array or both. ◦ mysql_fetch_assoc($result) : Return a row of data from the query ’ s result set as an associative array. ◦ mysql_error([$resource]) : Shows the error message generated by the previous query. ◦ die(<String> $msg) die() prints message and exits the current script.
  • 7. Cont… To connect with database ◦ $con = mysql_connect ($host, $username, $password) $host = ‘localhost’; $user = ‘root’; $pass = ‘’; $con = mysql_connect($host, $user, $pass); The following statement has the same effect: $con = mysql_connect(‘localhost’, ‘root’, ‘’); To close the connection ◦ mysql_close($con); To select database $db = mysql_select_db(DBName,$con)
  • 8. Create Table Syntax:- ◦ CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... ) Example:- ◦ CREATE TABLE Persons ( FirstName varchar(15), LastName varchar(15), Age int ) Important: A database must be selected before a table can be created. The database is selected with the mysql_select_db() function.
  • 9. Insert data into tables The INSERT INTO statement is used to add new records to a database table. It is possible to write the INSERT INTO statement in two forms. The first form doesn't specify the column names where the data will be inserted, only their values: INSERT INTO table_name VALUES (value1, value2, value3,...) The second form specifies both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) To get PHP to execute the statements above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example:- // insert data into table $insert=mysql_query("INSERT INTO Persons VALUES (1, 'Glenn', 'Quagmire',33 )"); // Execute query mysql_query($insert,$con); // insert data into table $insert=mysql_query("INSERT INTO Persons (personID,FirstName, LastName, Age) VALUES (2,'Peter', 'Griffin',35)");
  • 10. Insert data into table using FORM<html> <body> <form action="insert.php" method="post"> Firstname: <input type="text" name="firstname"> Lastname: <input type="text" name="lastname"> Age: <input type="text" name="age"> <input type="submit"> </form> </body> </html> When a user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.php".
  • 11. Here is the "insert.php" page: <?php $con = mysql_connect('localhost', 'root', '') or die ('Unable to connect. Check your connection parameters.'); echo "Connection successfullyn"; // select database mysql_select_db('student', $con) or die(mysql_error($con)); echo "Database activen"; //insert data $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con); ?>
  • 12. Retrieve the Data From a Database Table$result = mysql_query("select * from Persons ") To retrive the data from the table we are using the mysql_fetch_array() function. When we pass $result into the mysql_fetch_array function -- mysql_fetch_array($result) -- an associative array (firstname, lastname, age) is returned. mysql_fetch_array() function to return the first row from the recordset as an array. In our MySQL table " Persons," there are only three fields that we care about: firstname, lastname and age. These names are the keys to extracting the data from our associative array. To get the firstname we use $row[‘firstname'] , to get the lastname we use $row[‘lastnamr'] and to get the age we use $row['age'].
  • 13. fetch array while loopEach call to mysql_fetch_array() returns the next row in the recordset. $result = mysql_query("SELECT * FROM Persons"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName'].””.$row[‘age’]; echo "<br />"; } The while loop loops through all the records in the recordset. To print the value of each row, we use the PHP $row variable ($row['FirstName'] ,$row['LastName'],$row[‘age’]).
  • 14. Retrieving data To retrieving the data from database 2 function are used. ◦ mysql_fetch_array() ◦ mysql_fetch_assoc() The mysql_fetch_assoc() function returns a single row from the table as an associative array. The data can be retrieved by using the column names as indexes. The mysql_fetch_array() function returns a single row from the table. The data can be retrieved by column names and column indexes. @ is used to generate user defined exception other than System generated errors. mysql_num_fields( $result ) is used to count total number of fields and coloumn from your database. $num_cols = mysql_num_fields( $result ); mysql_num_rows( $result ) is used to count total number of recods from your database. $num_rows = mysql_num_rows( $result );
  • 15. Include() AND include_once() Include() AND require():- ◦ The include and require statements are used to insert useful codes written in other files, in the flow of execution. ◦ Include and require are identical, except upon failure: require will produce a fatal error (E_COMPILE_ERROR) and stop the script include will only produce a warning (E_WARNING) and the script will continue So, if you want the execution to go on and show users the output, even if the include file is missing, use include(). Otherwise, require(). ◦ Syntax:- Include(“file name with path”); or include “file name with path”; Require(“file name with path”); or require “file name with path”; ◦ Example:- <html> <body> <?php include 'header.php'; ?> <h1>Welcome to my home page!</h1> <p>Some text.</p> </body> </html>
  • 16. Include_once() AND require_once() Include_once() & require_once() both are functioning same as include() and require. But the main difference between those function is include_once() and require_once() include file only once while include() and require() include files as many time as you want. ◦ Syntax:- Include_once(“file name with path”); or include_once “file name with path”; Require_once(“file name with path”); or require_once “file name with path”; ◦ Example:- <html> <body> <?php include_once 'header.php'; ?> <h1>Welcome to my home page!</h1> <p>Some text.</p> </body> </html>
  • 17. Maintaining State in PHP using Cookies & Sessions Why to maintain state in php? ◦ HTTP is stateless Protocol. ◦ Any data you have stored is forgotten about when the page has been sent to the client and the connection is closed. ◦ Cookie is tiny bits of information that a web site could store on the client's machine that were sent back to the web site each time a new page was requested. Each cookie could only be read by the web site that had written it.
  • 18. What is a Cookie? A cookie is a small text file that is stored on a user’s computer. Each cookie on the user’s computer is connected to a particular domain. Each cookie be used to store up to 4kB of data. A maximum of 20 cookies can be stored on a user’s PC per domain.
  • 19. 1. User sends a request for page at www.example.com for the first time. Exampl e page request
  • 20. 2. Server sends back the page xhtml to the browser AND stores some data in a cookie on the user’s PC. Exampl e cookie data xhtml
  • 21. 3. At the next page request for domain www.example.com, all cookie data associated with this domain is sent too. Exampl e page request cookie data
  • 22. setcookie(name [,value [,expire [,path [,domain [,secure]]]]]) name = cookie name value = data to store (string) expire = UNIX timestamp when the cookie expires. Default is that cookie expires when browser is closed. path = Path on the server within and below which the cookie is available on. domain = Domain at which the cookie is available for. secure = If cookie should be sent over HTTPS connection only. Default false. Set a cookie
  • 23. setcookie(‘name’,’Robert’) This command will set the cookie called name on the user’s PC containing the data Robert. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted when the browser is closed (default expire). setcookie(‘age’,’20’,time()+60*60*24*30) This command will set the cookie called age on the user’s PC containing the data 20. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted after 30 days. Set a cookie - examples
  • 24. As the setcookie command involves sending a HTTP header request, it must be executed before any xhtml is echoed to the browser, including whitespace. Where to write code for Cookie… correct! incorrect. echoed whitespace before setcookie
  • 25. All cookie data is available through the superglobal $_COOKIE: $variable = $_COOKIE[‘cookie_name’] or $variable = $HTTP_COOKIE_VARS[‘cookie_name’]; e.g. $age = $_COOKIE[‘age’] Read cookie data
  • 26. To remove a cookie, simply overwrite the cookie with a new one with an expiry time in the past… setcookie(‘cookie_name’,’’,time()- 6000) Delete a cookie
  • 27. You can store user information (e.g. username, items selected, etc.) in the server side for later use using PHP session. Sessions work by creating a unique id (UID) for each visitor and storing variables based on this UID. The UID is either stored in a cookie or is propagated in the URL. PHP Sessions <?php session_start(); ?> <html> <body> </body> </html> session_start() function must appear BEFORE the <html> tag. Before you can store user information in your PHP session, you must first start up the session.
  • 28. PHP Sessions Starting a PHP session: <?php session_start(); ?> • This tells PHP that a session is requested. • A session ID is then allocated at the server end. • session ID looks like: sess_f1234781237468123768asjkhfa78912 34g
  • 29.  $_SESSION  e.g., $_SESSION[“intVar”] = 10;  Testing if a session variable has been set: session_start(); if(!$_SESSION['intVar']) {...} //intVar is set or not Session variables
  • 30. Session Example 1<?php session_start(); if (!isset($_SESSION["intVar"]) ){ $_SESSION["intVar"] = 1; } else { $_SESSION["intVar"]++; } echo "<p>In this session you have accessed this page " . $_SESSION["intVar"] . "times.</p>"; ?>
  • 31. Ending sessionsunset($_SESSION[‘name’]) –Remove a session variable session_destroy() – Destroys all data registered to a session – does not unset session global variables and cookies associated with the session –Not normally done - leave to timeout