SlideShare a Scribd company logo
PHP MYSQL
COURSE INSTRUCTOR: Akram Ali Omar
Email: akram.ali.omar@gmail.com
Mobile: +255778695626
The State University Of Zanzibar 1
DINF - DCS 0212: Interactive Website Development
Opening and Closing a MySQL Connection
• Open a connection to a MySQL database server with the mysql_connect()
function
• The mysql_connect() function returns a positive integer if it connects to the
database successfully or FALSE if it does not
• Assign the return value from the mysql_connect() function to a variable that
you can use to access the database in your script
mysqli extension
• The mysqli extension features are dual interface.
• It supports the procedural and object-oriented programming paradigm
• Users migrating from the old mysql extension may prefer the procedural
interface.
• The procedural interface is similar to that of the old mysql extension.
• There are no significant performance differences between the two
interfaces. Users can base their choice on personal preference.
• In many cases, the function names differ only by prefix
Mixing styles
• It is possible to switch between styles at any time. Mixing both styles is not
recommended for code clarity and coding style reasons
• Bad coding style
$conn = new mysqli("example.com", "user", "password", "database");
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
}
$res = mysqli_query($conn, "SELECT 'Possible but bad style.' AS _msg FROM
DUAL");
if (!$res) {
echo "Failed to run query: (" . $conn->errno . ") " . $conn->error;
}
if ($row = $res->fetch_assoc()) {
echo $row['_msg'];
}
?>
Connecting to MySQL
• Open a connection to a MySQL database server using
1. Using procedural interface
2. Using Object-oriented
<?php
$conn = mysqli_connect("example.com", "user", "password", "database");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($conn);
?>
<?php
$conn = new Mysqli("example.com", "user", "password", "database");
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
}
$conn->close();
?>
Reporting MySQL Errors
• Reasons for not connecting to a database server include:
 The database server is not running
 Insufficient privileges to access the data source
 Invalid username and/or password
• Use mysqli_errno()(procedural interface) and $conn-> errno(Object-
oriented) to returns the error code from the last attempted MySQL
function call or 0 if no error occurred
• Use mysqli_error() and $conn->error to return the error message of the
previous mysqli*() function 6
Suppressing Errors with the Error Control
Operator
• By default, functions in the mysqli package display errors and warnings as
they occur
• Use the error control operator (@) to suppress error messages
7
Terminating Script Execution
• The die() and exit() functions terminate script execution
• The die() version is usually used when attempting to access a data source
• Both functions accept a single string argument
• Call the die() and exit() functions as separate statements or by appending
either function to an expression with the or operator
8
Reporting MySQL Errors
• Open a connection to a MySQL database server using
1. Using procedural interface
2. Using Object-oriented
<?php
$conn = @mysqli_connect("example.com", "user", "password", "database");
if (mysqli_connect_errno($conn)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
mysqli_close($conn);
?>
<?php
$conn = @new mysqli("example.com", "user", "password", "database");
if ($conn->connect_errno) {
die("Failed to connect to MySQL: " . $conn->connect_error);
}
$conn->close();
?>
Reporting MySQL Errors
• Open a connection to a MySQL database server using
1. Using procedural interface
2. Using Object-oriented
<?php
$conn = @mysqli_connect("example.com", "user", "password", "database")or
die("Failed to connect to MySQL: ". mysqli_connect_error() );
mysqli_close($conn);
?>
<?php
$conn = @new mysqli("example.com", "user", "password", "database") or
die("Failed to connect to MySQL: " . $conn->connect_error);
$conn->close();
?>
Executing SQL Statements
• Use the mysqli_query(query) [procedural interface] and query(query)
[Object-oriented] functions to send SQL statements to MySQL
• The mysqli_query() and query(query) functions return one of three
values:
For SQL statements that do not return results (CREATE
DATABASE and CREATE TABLE statements) it returns a value of
TRUE if the statement executes successfully
11
Executing SQL Statements (continued)
• For SQL statements that return results (SELECT and SHOW
statements) the mysqli_query() and query() functions returns a result
pointer that represents the query results
 A result pointer is a special type of variable that refers to the
currently selected row in a resultset
• The mysqli_query() and query() functions return a value of FALSE for
any SQL statements that fail, regardless of whether they return results
12
Retrieving Records into an Indexed Array
• The mysqli_fetch_row()[procedural] and fetch_row()[Object oriented]
functions return the fields in the current row of a result set into an
indexed array and moves the result pointer to the next row
Retrieving Records into an Indexed Array and
display into HTML table
$SQLstring = "SELECT * FROM company_cars";
$QueryResult = @mysqli_query($SQLstring, $conn);
echo "<table width='100%' border='1'>";
echo "<tr><th>License</th><th>Make</th><th>Model</th>
<th>Mileage</th><th>Year</th></tr>";
while ($Row = mysqli_fetch_row($QueryResult)) {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td>";
echo "<td>{$Row[4]}</td></tr>"; }
echo "</table>";
Retrieving Records into an Indexed Array
$SQLstring = "SELECT * FROM company_cars";
$QueryResult = @$conn->query($SQLstring);
echo "<table width='100%' border='1'>";
echo "<tr><th>License</th><th>Make</th><th>Model</th>
<th>Mileage</th><th>Year</th></tr>";
while ($Row = $conn->fetch_row($QueryResult)) {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td>";
echo "<td>{$Row[4]}</td></tr>"; }
echo "</table>";
Retrieving Records into an Indexed Array
16
Retrieving Records into an Associative Array
• The mysqli_fetch_assoc()[procedural] and fetch_assoc()[Object Oriented]
function returns the fields in the current row of a resultset into an associative
array and moves the result pointer to the next row
• The difference between mysqli_fetch_assoc() and mysqli_fetch_row() is that
instead of returning the fields into an indexed array, the mysqli_fetch_assoc()
function returns the fields into an associate array and uses each field name as
the array key
• You can also use mysqli_fetch_array()[procedural] or fetch_array()[Object
Oriented]which returns field in both indexing and associative array
17
Accessing Query Result Information
• The mysqli_num_rows()[function] function or $results-
>num_rows[Object oriented] returns the number of rows in a
query result
• The mysqli_num_fields() function returns the number of fields in
a query result
• Both functions accept a database connection variable as an
argument
18
Accessing Query Result Information (continued)
$SQLstring = "SELECT * FROM company_cars";
$QueryResult = @mysqli_query($SQLstring, $conn) or
die(mysqli_error());
echo "<p>Successfully executed the query.</p>";
$NumRows = mysqli_num_rows($QueryResult);
$NumFields = mysqli_num_fields($QueryResult);
if ($NumRows != 0 && $NumFields != 0){
echo "<p>Your query returned " .
mysqli_num_rows($QueryResult) . " rows and ".
mysqli_num_fields($QueryResult) . " fields.</p>";
}else{
echo "<p>Your query returned no results.</p>";}
mysqli_close($conn);
Accessing Query Result Information (continued)
$SQLstring = "SELECT * FROM company_cars";
$QueryResult = @$conn->query($SQLstring, $conn) or
die($conn->error);
echo "<p>Successfully executed the query.</p>";
$NumRows = $QueryResult->num_rows;
$NumFields = $QueryResult->num_fields;
if ($NumRows != 0 && $NumFields != 0){
echo "<p>Your query returned " . $QueryResult-
>num_rows. " rows and ". $QueryResult-> num_fields.
" fields.</p>";
}else{
echo "<p>Your query returned no results.</p>";}
$conn->close();
Accessing Query Result Information (continued)
Closing Query Results
• When you are finished working with query results retrieved with the
mysqli_query() function, use the mysqli_free_result() function to close
the resultset
• To close the resultset, pass to the mysqli_free_result() function the
variable containing the result pointer from the mysqli_query() function
22
Inserting Record into Table
<?php
$conn = mysqli_connect("…","…","…,"…")or die('Could not
connect: ' . mysqli_error());
mysqli_query("INSERT INTO Persons (FirstName, LastName,
Age) VALUES ('Peter','Griffin','35')");
mysqli_query("INSERT INTO Persons (FirstName, LastName,
Age)
VALUES ('Glenn', ‘Brown', '33')");
mysqli_close($conn);
?>
23
Delete Record
<?php
$conn = mysqli_connect("…","…","…,"…")or die('Could not
connect: ' . mysqli_error());
$sql = “DELETE FROM Persons WHERE FirstName = ‘Peter’
AND LastName = “Griffin’”);
mysqli_query($conn ,$sql);
mysqli_close($conn);
?>
24
Update Record
25
<?php
$conn = mysqli_connect("…","…","…,"…")or die('Could not
connect: ' . mysqli_error());
$sql = “UPDATE Persons SET Age = ’36’ WHERE FirstName =
‘Peter’
AND LastName = “Griffin’”;
mysqli_query($sql, $conn)or die(mysqli_error());
mysqli_close($conn);
?>
Using the mysqli_affected_rows() Function
• With queries that return results (SELECT queries), use the
mysqli_num_rows() function to find the number of records returned from
the query
• With queries that modify tables but do not return results (INSERT,
UPDATE, and DELETE queries), use the mysqli_affected_rows()
function to determine the number of affected rows
26
Using the mysql_affected_rows() Function
(continued)
$SQLstring = "UPDATE company_cars SET mileage=50112.3
WHERE license='AK-1234'";
$QueryResult = @mysqli_query($SQLstring, $conn)or
die(mysqli_error());
echo "<p>Successfully updated "
. mysqli_affected_rows($conn) . "
record(s).</p>";
27
Using the mysql_affected_rows() Function
(continued)
28
The State University Of Zanzibar 29
Ad

More Related Content

Similar to lecture 7 - Introduction to MySQL with PHP.pptx (20)

4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
Jalpesh Vasa
 
Stored Procedure
Stored ProcedureStored Procedure
Stored Procedure
NidiaRamirez07
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for Newbies
Dave Stokes
 
CHAPTER six DataBase Driven Websites.pptx
CHAPTER six DataBase Driven Websites.pptxCHAPTER six DataBase Driven Websites.pptx
CHAPTER six DataBase Driven Websites.pptx
KelemAlebachew
 
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
berihun18
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
salissal
 
Web Application Development using PHP Chapter 7
Web Application Development using PHP Chapter 7Web Application Development using PHP Chapter 7
Web Application Development using PHP Chapter 7
Mohd Harris Ahmad Jaal
 
Basics of Working with PHP and MySQL.pptx
Basics of Working with PHP and MySQL.pptxBasics of Working with PHP and MySQL.pptx
Basics of Working with PHP and MySQL.pptx
jensas21
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
okelloerick
 
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
FYBSC IT Web Programming Unit V  Advanced PHP and MySQLFYBSC IT Web Programming Unit V  Advanced PHP and MySQL
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
Arti Parab Academics
 
Database Management - Lecture 4 - PHP and Mysql
Database Management - Lecture 4 - PHP and MysqlDatabase Management - Lecture 4 - PHP and Mysql
Database Management - Lecture 4 - PHP and Mysql
Al-Mamun Sarkar
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptx
CynthiaKendi1
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
elliando dias
 
PHP Database Programming Basics -- Northeast PHP
PHP Database Programming Basics -- Northeast PHPPHP Database Programming Basics -- Northeast PHP
PHP Database Programming Basics -- Northeast PHP
Dave Stokes
 
Database presentation
Database presentationDatabase presentation
Database presentation
webhostingguy
 
Php Mysql
Php Mysql Php Mysql
Php Mysql
Mudasir Syed
 
3 php-connect-to-my sql
3 php-connect-to-my sql3 php-connect-to-my sql
3 php-connect-to-my sql
Achchuthan Yogarajah
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
chapter_Seven Database manipulation using php.pptx
chapter_Seven Database manipulation using php.pptxchapter_Seven Database manipulation using php.pptx
chapter_Seven Database manipulation using php.pptx
Getawu
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for Newbies
Dave Stokes
 
CHAPTER six DataBase Driven Websites.pptx
CHAPTER six DataBase Driven Websites.pptxCHAPTER six DataBase Driven Websites.pptx
CHAPTER six DataBase Driven Websites.pptx
KelemAlebachew
 
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
berihun18
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
salissal
 
Web Application Development using PHP Chapter 7
Web Application Development using PHP Chapter 7Web Application Development using PHP Chapter 7
Web Application Development using PHP Chapter 7
Mohd Harris Ahmad Jaal
 
Basics of Working with PHP and MySQL.pptx
Basics of Working with PHP and MySQL.pptxBasics of Working with PHP and MySQL.pptx
Basics of Working with PHP and MySQL.pptx
jensas21
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
okelloerick
 
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
FYBSC IT Web Programming Unit V  Advanced PHP and MySQLFYBSC IT Web Programming Unit V  Advanced PHP and MySQL
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
Arti Parab Academics
 
Database Management - Lecture 4 - PHP and Mysql
Database Management - Lecture 4 - PHP and MysqlDatabase Management - Lecture 4 - PHP and Mysql
Database Management - Lecture 4 - PHP and Mysql
Al-Mamun Sarkar
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptx
CynthiaKendi1
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
elliando dias
 
PHP Database Programming Basics -- Northeast PHP
PHP Database Programming Basics -- Northeast PHPPHP Database Programming Basics -- Northeast PHP
PHP Database Programming Basics -- Northeast PHP
Dave Stokes
 
Database presentation
Database presentationDatabase presentation
Database presentation
webhostingguy
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
chapter_Seven Database manipulation using php.pptx
chapter_Seven Database manipulation using php.pptxchapter_Seven Database manipulation using php.pptx
chapter_Seven Database manipulation using php.pptx
Getawu
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 

More from AOmaAli (15)

Lecture 3 Introduction to HTML FORM AND CSS.pptx
Lecture 3 Introduction to HTML FORM AND CSS.pptxLecture 3 Introduction to HTML FORM AND CSS.pptx
Lecture 3 Introduction to HTML FORM AND CSS.pptx
AOmaAli
 
Lecture 9 - Intruduction to BOOTSTRAP.pptx
Lecture 9 - Intruduction to BOOTSTRAP.pptxLecture 9 - Intruduction to BOOTSTRAP.pptx
Lecture 9 - Intruduction to BOOTSTRAP.pptx
AOmaAli
 
Lecture 6: Introduction to PHP and Mysql .pptx
Lecture 6:  Introduction to PHP and Mysql .pptxLecture 6:  Introduction to PHP and Mysql .pptx
Lecture 6: Introduction to PHP and Mysql .pptx
AOmaAli
 
3-itec229 sddds dfsddfdf dfdfdf _chapter1.ppt
3-itec229 sddds dfsddfdf dfdfdf _chapter1.ppt3-itec229 sddds dfsddfdf dfdfdf _chapter1.ppt
3-itec229 sddds dfsddfdf dfdfdf _chapter1.ppt
AOmaAli
 
Instructional Design - Storyboard_IT Teaching Methods_ED 2216_MSM.pdf
Instructional Design - Storyboard_IT Teaching Methods_ED 2216_MSM.pdfInstructional Design - Storyboard_IT Teaching Methods_ED 2216_MSM.pdf
Instructional Design - Storyboard_IT Teaching Methods_ED 2216_MSM.pdf
AOmaAli
 
SSdsdc dssdsd sfdddsd sdsds assas sdsddsdsdAD.pptx
SSdsdc  dssdsd sfdddsd sdsds assas sdsddsdsdAD.pptxSSdsdc  dssdsd sfdddsd sdsds assas sdsddsdsdAD.pptx
SSdsdc dssdsd sfdddsd sdsds assas sdsddsdsdAD.pptx
AOmaAli
 
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptxLECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
AOmaAli
 
Lecture 2 Software Development Process and SDCL models.pptx
Lecture 2 Software Development Process and SDCL models.pptxLecture 2 Software Development Process and SDCL models.pptx
Lecture 2 Software Development Process and SDCL models.pptx
AOmaAli
 
LECTURE 2 -Object oriented Java Basics.pptx
LECTURE 2 -Object oriented  Java Basics.pptxLECTURE 2 -Object oriented  Java Basics.pptx
LECTURE 2 -Object oriented Java Basics.pptx
AOmaAli
 
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptxLECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
AOmaAli
 
Software development life cycle (SDLC) Models
Software development life cycle (SDLC) ModelsSoftware development life cycle (SDLC) Models
Software development life cycle (SDLC) Models
AOmaAli
 
LECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptxLECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptx
AOmaAli
 
LECTURE 12 WINDOWS FORMS PART 2.pptx
LECTURE 12 WINDOWS FORMS PART 2.pptxLECTURE 12 WINDOWS FORMS PART 2.pptx
LECTURE 12 WINDOWS FORMS PART 2.pptx
AOmaAli
 
LECTURE 1 - Introduction to Programming.pptx
LECTURE 1 - Introduction to Programming.pptxLECTURE 1 - Introduction to Programming.pptx
LECTURE 1 - Introduction to Programming.pptx
AOmaAli
 
LECTURE 1-Introduction to mobile communication systems.pptx
LECTURE 1-Introduction to mobile communication systems.pptxLECTURE 1-Introduction to mobile communication systems.pptx
LECTURE 1-Introduction to mobile communication systems.pptx
AOmaAli
 
Lecture 3 Introduction to HTML FORM AND CSS.pptx
Lecture 3 Introduction to HTML FORM AND CSS.pptxLecture 3 Introduction to HTML FORM AND CSS.pptx
Lecture 3 Introduction to HTML FORM AND CSS.pptx
AOmaAli
 
Lecture 9 - Intruduction to BOOTSTRAP.pptx
Lecture 9 - Intruduction to BOOTSTRAP.pptxLecture 9 - Intruduction to BOOTSTRAP.pptx
Lecture 9 - Intruduction to BOOTSTRAP.pptx
AOmaAli
 
Lecture 6: Introduction to PHP and Mysql .pptx
Lecture 6:  Introduction to PHP and Mysql .pptxLecture 6:  Introduction to PHP and Mysql .pptx
Lecture 6: Introduction to PHP and Mysql .pptx
AOmaAli
 
3-itec229 sddds dfsddfdf dfdfdf _chapter1.ppt
3-itec229 sddds dfsddfdf dfdfdf _chapter1.ppt3-itec229 sddds dfsddfdf dfdfdf _chapter1.ppt
3-itec229 sddds dfsddfdf dfdfdf _chapter1.ppt
AOmaAli
 
Instructional Design - Storyboard_IT Teaching Methods_ED 2216_MSM.pdf
Instructional Design - Storyboard_IT Teaching Methods_ED 2216_MSM.pdfInstructional Design - Storyboard_IT Teaching Methods_ED 2216_MSM.pdf
Instructional Design - Storyboard_IT Teaching Methods_ED 2216_MSM.pdf
AOmaAli
 
SSdsdc dssdsd sfdddsd sdsds assas sdsddsdsdAD.pptx
SSdsdc  dssdsd sfdddsd sdsds assas sdsddsdsdAD.pptxSSdsdc  dssdsd sfdddsd sdsds assas sdsddsdsdAD.pptx
SSdsdc dssdsd sfdddsd sdsds assas sdsddsdsdAD.pptx
AOmaAli
 
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptxLECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
AOmaAli
 
Lecture 2 Software Development Process and SDCL models.pptx
Lecture 2 Software Development Process and SDCL models.pptxLecture 2 Software Development Process and SDCL models.pptx
Lecture 2 Software Development Process and SDCL models.pptx
AOmaAli
 
LECTURE 2 -Object oriented Java Basics.pptx
LECTURE 2 -Object oriented  Java Basics.pptxLECTURE 2 -Object oriented  Java Basics.pptx
LECTURE 2 -Object oriented Java Basics.pptx
AOmaAli
 
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptxLECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
AOmaAli
 
Software development life cycle (SDLC) Models
Software development life cycle (SDLC) ModelsSoftware development life cycle (SDLC) Models
Software development life cycle (SDLC) Models
AOmaAli
 
LECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptxLECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptx
AOmaAli
 
LECTURE 12 WINDOWS FORMS PART 2.pptx
LECTURE 12 WINDOWS FORMS PART 2.pptxLECTURE 12 WINDOWS FORMS PART 2.pptx
LECTURE 12 WINDOWS FORMS PART 2.pptx
AOmaAli
 
LECTURE 1 - Introduction to Programming.pptx
LECTURE 1 - Introduction to Programming.pptxLECTURE 1 - Introduction to Programming.pptx
LECTURE 1 - Introduction to Programming.pptx
AOmaAli
 
LECTURE 1-Introduction to mobile communication systems.pptx
LECTURE 1-Introduction to mobile communication systems.pptxLECTURE 1-Introduction to mobile communication systems.pptx
LECTURE 1-Introduction to mobile communication systems.pptx
AOmaAli
 
Ad

Recently uploaded (20)

Mastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdfMastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdf
Spiral Mantra
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
MINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PRMINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PR
MIND CTI
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
TrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token ListingTrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token Listing
Trs Labs
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Social Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTechSocial Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTech
Steve Jonas
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Mastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdfMastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdf
Spiral Mantra
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
MINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PRMINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PR
MIND CTI
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
TrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token ListingTrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token Listing
Trs Labs
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Social Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTechSocial Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTech
Steve Jonas
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Ad

lecture 7 - Introduction to MySQL with PHP.pptx

  • 1. PHP MYSQL COURSE INSTRUCTOR: Akram Ali Omar Email: [email protected] Mobile: +255778695626 The State University Of Zanzibar 1 DINF - DCS 0212: Interactive Website Development
  • 2. Opening and Closing a MySQL Connection • Open a connection to a MySQL database server with the mysql_connect() function • The mysql_connect() function returns a positive integer if it connects to the database successfully or FALSE if it does not • Assign the return value from the mysql_connect() function to a variable that you can use to access the database in your script
  • 3. mysqli extension • The mysqli extension features are dual interface. • It supports the procedural and object-oriented programming paradigm • Users migrating from the old mysql extension may prefer the procedural interface. • The procedural interface is similar to that of the old mysql extension. • There are no significant performance differences between the two interfaces. Users can base their choice on personal preference. • In many cases, the function names differ only by prefix
  • 4. Mixing styles • It is possible to switch between styles at any time. Mixing both styles is not recommended for code clarity and coding style reasons • Bad coding style $conn = new mysqli("example.com", "user", "password", "database"); if ($conn->connect_errno) { echo "Failed to connect to MySQL: " . $conn->connect_error; } $res = mysqli_query($conn, "SELECT 'Possible but bad style.' AS _msg FROM DUAL"); if (!$res) { echo "Failed to run query: (" . $conn->errno . ") " . $conn->error; } if ($row = $res->fetch_assoc()) { echo $row['_msg']; } ?>
  • 5. Connecting to MySQL • Open a connection to a MySQL database server using 1. Using procedural interface 2. Using Object-oriented <?php $conn = mysqli_connect("example.com", "user", "password", "database"); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_close($conn); ?> <?php $conn = new Mysqli("example.com", "user", "password", "database"); if ($conn->connect_errno) { echo "Failed to connect to MySQL: " . $conn->connect_error; } $conn->close(); ?>
  • 6. Reporting MySQL Errors • Reasons for not connecting to a database server include:  The database server is not running  Insufficient privileges to access the data source  Invalid username and/or password • Use mysqli_errno()(procedural interface) and $conn-> errno(Object- oriented) to returns the error code from the last attempted MySQL function call or 0 if no error occurred • Use mysqli_error() and $conn->error to return the error message of the previous mysqli*() function 6
  • 7. Suppressing Errors with the Error Control Operator • By default, functions in the mysqli package display errors and warnings as they occur • Use the error control operator (@) to suppress error messages 7
  • 8. Terminating Script Execution • The die() and exit() functions terminate script execution • The die() version is usually used when attempting to access a data source • Both functions accept a single string argument • Call the die() and exit() functions as separate statements or by appending either function to an expression with the or operator 8
  • 9. Reporting MySQL Errors • Open a connection to a MySQL database server using 1. Using procedural interface 2. Using Object-oriented <?php $conn = @mysqli_connect("example.com", "user", "password", "database"); if (mysqli_connect_errno($conn)) { die("Failed to connect to MySQL: " . mysqli_connect_error()); } mysqli_close($conn); ?> <?php $conn = @new mysqli("example.com", "user", "password", "database"); if ($conn->connect_errno) { die("Failed to connect to MySQL: " . $conn->connect_error); } $conn->close(); ?>
  • 10. Reporting MySQL Errors • Open a connection to a MySQL database server using 1. Using procedural interface 2. Using Object-oriented <?php $conn = @mysqli_connect("example.com", "user", "password", "database")or die("Failed to connect to MySQL: ". mysqli_connect_error() ); mysqli_close($conn); ?> <?php $conn = @new mysqli("example.com", "user", "password", "database") or die("Failed to connect to MySQL: " . $conn->connect_error); $conn->close(); ?>
  • 11. Executing SQL Statements • Use the mysqli_query(query) [procedural interface] and query(query) [Object-oriented] functions to send SQL statements to MySQL • The mysqli_query() and query(query) functions return one of three values: For SQL statements that do not return results (CREATE DATABASE and CREATE TABLE statements) it returns a value of TRUE if the statement executes successfully 11
  • 12. Executing SQL Statements (continued) • For SQL statements that return results (SELECT and SHOW statements) the mysqli_query() and query() functions returns a result pointer that represents the query results  A result pointer is a special type of variable that refers to the currently selected row in a resultset • The mysqli_query() and query() functions return a value of FALSE for any SQL statements that fail, regardless of whether they return results 12
  • 13. Retrieving Records into an Indexed Array • The mysqli_fetch_row()[procedural] and fetch_row()[Object oriented] functions return the fields in the current row of a result set into an indexed array and moves the result pointer to the next row
  • 14. Retrieving Records into an Indexed Array and display into HTML table $SQLstring = "SELECT * FROM company_cars"; $QueryResult = @mysqli_query($SQLstring, $conn); echo "<table width='100%' border='1'>"; echo "<tr><th>License</th><th>Make</th><th>Model</th> <th>Mileage</th><th>Year</th></tr>"; while ($Row = mysqli_fetch_row($QueryResult)) { echo "<tr><td>{$Row[0]}</td>"; echo "<td>{$Row[1]}</td>"; echo "<td>{$Row[2]}</td>"; echo "<td align='right'>{$Row[3]}</td>"; echo "<td>{$Row[4]}</td></tr>"; } echo "</table>";
  • 15. Retrieving Records into an Indexed Array $SQLstring = "SELECT * FROM company_cars"; $QueryResult = @$conn->query($SQLstring); echo "<table width='100%' border='1'>"; echo "<tr><th>License</th><th>Make</th><th>Model</th> <th>Mileage</th><th>Year</th></tr>"; while ($Row = $conn->fetch_row($QueryResult)) { echo "<tr><td>{$Row[0]}</td>"; echo "<td>{$Row[1]}</td>"; echo "<td>{$Row[2]}</td>"; echo "<td align='right'>{$Row[3]}</td>"; echo "<td>{$Row[4]}</td></tr>"; } echo "</table>";
  • 16. Retrieving Records into an Indexed Array 16
  • 17. Retrieving Records into an Associative Array • The mysqli_fetch_assoc()[procedural] and fetch_assoc()[Object Oriented] function returns the fields in the current row of a resultset into an associative array and moves the result pointer to the next row • The difference between mysqli_fetch_assoc() and mysqli_fetch_row() is that instead of returning the fields into an indexed array, the mysqli_fetch_assoc() function returns the fields into an associate array and uses each field name as the array key • You can also use mysqli_fetch_array()[procedural] or fetch_array()[Object Oriented]which returns field in both indexing and associative array 17
  • 18. Accessing Query Result Information • The mysqli_num_rows()[function] function or $results- >num_rows[Object oriented] returns the number of rows in a query result • The mysqli_num_fields() function returns the number of fields in a query result • Both functions accept a database connection variable as an argument 18
  • 19. Accessing Query Result Information (continued) $SQLstring = "SELECT * FROM company_cars"; $QueryResult = @mysqli_query($SQLstring, $conn) or die(mysqli_error()); echo "<p>Successfully executed the query.</p>"; $NumRows = mysqli_num_rows($QueryResult); $NumFields = mysqli_num_fields($QueryResult); if ($NumRows != 0 && $NumFields != 0){ echo "<p>Your query returned " . mysqli_num_rows($QueryResult) . " rows and ". mysqli_num_fields($QueryResult) . " fields.</p>"; }else{ echo "<p>Your query returned no results.</p>";} mysqli_close($conn);
  • 20. Accessing Query Result Information (continued) $SQLstring = "SELECT * FROM company_cars"; $QueryResult = @$conn->query($SQLstring, $conn) or die($conn->error); echo "<p>Successfully executed the query.</p>"; $NumRows = $QueryResult->num_rows; $NumFields = $QueryResult->num_fields; if ($NumRows != 0 && $NumFields != 0){ echo "<p>Your query returned " . $QueryResult- >num_rows. " rows and ". $QueryResult-> num_fields. " fields.</p>"; }else{ echo "<p>Your query returned no results.</p>";} $conn->close();
  • 21. Accessing Query Result Information (continued)
  • 22. Closing Query Results • When you are finished working with query results retrieved with the mysqli_query() function, use the mysqli_free_result() function to close the resultset • To close the resultset, pass to the mysqli_free_result() function the variable containing the result pointer from the mysqli_query() function 22
  • 23. Inserting Record into Table <?php $conn = mysqli_connect("…","…","…,"…")or die('Could not connect: ' . mysqli_error()); mysqli_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter','Griffin','35')"); mysqli_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', ‘Brown', '33')"); mysqli_close($conn); ?> 23
  • 24. Delete Record <?php $conn = mysqli_connect("…","…","…,"…")or die('Could not connect: ' . mysqli_error()); $sql = “DELETE FROM Persons WHERE FirstName = ‘Peter’ AND LastName = “Griffin’”); mysqli_query($conn ,$sql); mysqli_close($conn); ?> 24
  • 25. Update Record 25 <?php $conn = mysqli_connect("…","…","…,"…")or die('Could not connect: ' . mysqli_error()); $sql = “UPDATE Persons SET Age = ’36’ WHERE FirstName = ‘Peter’ AND LastName = “Griffin’”; mysqli_query($sql, $conn)or die(mysqli_error()); mysqli_close($conn); ?>
  • 26. Using the mysqli_affected_rows() Function • With queries that return results (SELECT queries), use the mysqli_num_rows() function to find the number of records returned from the query • With queries that modify tables but do not return results (INSERT, UPDATE, and DELETE queries), use the mysqli_affected_rows() function to determine the number of affected rows 26
  • 27. Using the mysql_affected_rows() Function (continued) $SQLstring = "UPDATE company_cars SET mileage=50112.3 WHERE license='AK-1234'"; $QueryResult = @mysqli_query($SQLstring, $conn)or die(mysqli_error()); echo "<p>Successfully updated " . mysqli_affected_rows($conn) . " record(s).</p>"; 27
  • 28. Using the mysql_affected_rows() Function (continued) 28
  • 29. The State University Of Zanzibar 29