SlideShare a Scribd company logo
Working With PHP And DBs
Working With PHP And DBsIntroduction to PHP & DB
The Native Interface
The ODBC Interface
The ORM Model & Interface
Q & AIntroduction To PHP & DBFor many people, the main reason for learning PHP is because of the interaction with databases it can offer.
It is surprising how useful a database can be when used with a website.
There is a huge variety of things you can do when you interact the two, from displaying simple lists to running a complete website from a database. Why Would We Want A Database?Some examples of PHP and DBs being used together are:
Banner Rotation - Each banner is generated by PHP script. This opens the DB and picks a random banner from it to show the visitor. It also counts the number of times the banner has been viewed.
Forums- All the pages and messages in the forum are stored in the DB and are presented and updated by PHP  scripts.Why Would We Want A Database?Some examples of PHP and DBs being used together cont’d:
Databases – Storing user login and personal information, images, articles, item stock, sales data etc. All of these task can be done easily using PHP scripts.
Reports – The most popular product on site, the best article, the biggest image. Visitor counters and trails, from which countries our visitors come from? All of these question can be answered easily using PHP scripts.PHP & SQL ServersSame Machine			    Same Network (LAN)	                 Over The Internet (WAN)	Internet(WAN)
 Supported Database TypesSome of the DBs that PHP supports:How Does PHP Use A Database?There are three major strategies for using a DB:
The Native Interface – PHP connects directly to the SQL server using its native protocol, e.g. MySQL protocol version 10.
The ODBC Interface – The ODBC driver is used as a mediator between the PHP and the SQL server. PHP uses the ODBC API which translates the SQL dialect.
The ORM Interface – PHP uses objects which are mapped to DB tables and elements.Famous Sites That Use PHP & DB
Working With PHP And DBsIntroduction to PHP & DB
The Native Interface
The ODBC Interface
The ORM Model & Interface
Q & A
The Native InterfacePHP connects directly to the SQL server using its native protocol, e.g. MySQL protocol version 10.
Pros: Best performance. No drivers or mediators are used, hence the connection and queries are performed in optimal speed.
Cons: Compatibility. Each DB vendor has his own SQL dialect. Native MySQL code won’t run on ORACLE and vice versa.PHP MethodologySimple steps to follow:
Create a connection to the database.
Select database.
Compose an SQL statement (query, creation etc).
Submit the statement to the database.
Receive results from the database.
Parse results and use them.
Close database connection. Repeat these steps for multiplestatements
<?php$link = mysql_connect('localhost', 'root', '') 	or die('Could not connect: ' . mysql_error());mysql_select_db(dbname') 	or die('Could not select database');?>MySQL ConnectionPHP connects to the MySQL server:UsernameComputerPassword
<?phpmysql_query("SET character_set_client = utf8");mysql_query("SET character_set_connection = utf8");mysql_query("SET character_set_results = utf8"); ?>MySQL UTF-8Working with UTF-8 (Hebrew).<?php$sql= "SELECT * FROM students WHERE ID > 5 order by id";$result = mysql_query($sql) 	or die ("Unable to SELECT FROM DB: ".$sql);while($line = mysql_fetch_array($result, MYSQL_ASSOC)){	echo $line["id"]."<br/>";}?>MySQL QueryPreparing, sending and receiving the query.MYSQL_ASSOC – Associative Array      MYSQL_NUM – Numeric Array

More Related Content

What's hot (20)

PPT
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
webhostingguy
 
PPTX
PHP FUNCTIONS
Zeeshan Ahmed
 
PPT
PHP - Introduction to PHP Fundamentals
Vibrant Technologies & Computers
 
PDF
Web Development Course: PHP lecture 2
Gheyath M. Othman
 
PPT
PHP complete reference with database concepts for beginners
Mohammed Mushtaq Ahmed
 
PPTX
Reaching Out From PL/SQL (OPP 2010)
Lucas Jellema
 
PDF
15 expression-language
snopteck
 
PPT
Php MySql For Beginners
Priti Solanki
 
PDF
Phpbasics
PrinceGuru MS
 
PDF
Doing more with LESS
jsmith92
 
PPTX
Introduction to php
Taha Malampatti
 
PPTX
Loops PHP 04
mohamedsaad24
 
PPT
Php mysql
Shehrevar Davierwala
 
PPT
Php Presentation
Manish Bothra
 
PPTX
Php Unit 1
team11vgnt
 
PPT
PHP Tutorials
Yuriy Krapivko
 
PPTX
Web programming
Leo Mark Villar
 
PDF
Rails vs Web2py
jonromero
 
PPT
php 1
tumetr1
 
PPT
html
tumetr1
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
webhostingguy
 
PHP FUNCTIONS
Zeeshan Ahmed
 
PHP - Introduction to PHP Fundamentals
Vibrant Technologies & Computers
 
Web Development Course: PHP lecture 2
Gheyath M. Othman
 
PHP complete reference with database concepts for beginners
Mohammed Mushtaq Ahmed
 
Reaching Out From PL/SQL (OPP 2010)
Lucas Jellema
 
15 expression-language
snopteck
 
Php MySql For Beginners
Priti Solanki
 
Phpbasics
PrinceGuru MS
 
Doing more with LESS
jsmith92
 
Introduction to php
Taha Malampatti
 
Loops PHP 04
mohamedsaad24
 
Php Presentation
Manish Bothra
 
Php Unit 1
team11vgnt
 
PHP Tutorials
Yuriy Krapivko
 
Web programming
Leo Mark Villar
 
Rails vs Web2py
jonromero
 
php 1
tumetr1
 
html
tumetr1
 

Viewers also liked (19)

PPTX
MySQLi
Ankit Bahuguna
 
PDF
Database Basics with PHP -- Connect JS Conference October 17th, 2015
Dave Stokes
 
PPTX
PHP - Beginner's Workshop
Rafael Pinto
 
PPT
Short Intro to PHP and MySQL
Jussi Pohjolainen
 
PPTX
Mysql Crud, Php Mysql, php, sql
Aimal Miakhel
 
PPT
Shubhrat mishra working with php 2
Shubhrat Mishra
 
PPT
PHP & MySQL 教學
Bo-Yi Wu
 
PDF
PHP CRUD Database Mysql
Yusuf A.H.
 
PPTX
CRUD html php mysql
Yesith Valencia
 
PPT
Database presentation
webhostingguy
 
PPTX
Technology labor ppt
Jaswinder Singh
 
PPTX
PHP Summer Training Presentation
Nitesh Sharma
 
PPT
Basic quality concepts(3)
ngiyari
 
PPT
MySql slides (ppt)
webhostingguy
 
PPT
Open Source Package PHP & MySQL
kalaisai
 
PPT
PHP Project PPT
Pankil Agrawal
 
PDF
Best Practices - PHP and the Oracle Database
Christopher Jones
 
PPT
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
PPTX
Impact of technology on education
Max Inder
 
Database Basics with PHP -- Connect JS Conference October 17th, 2015
Dave Stokes
 
PHP - Beginner's Workshop
Rafael Pinto
 
Short Intro to PHP and MySQL
Jussi Pohjolainen
 
Mysql Crud, Php Mysql, php, sql
Aimal Miakhel
 
Shubhrat mishra working with php 2
Shubhrat Mishra
 
PHP & MySQL 教學
Bo-Yi Wu
 
PHP CRUD Database Mysql
Yusuf A.H.
 
CRUD html php mysql
Yesith Valencia
 
Database presentation
webhostingguy
 
Technology labor ppt
Jaswinder Singh
 
PHP Summer Training Presentation
Nitesh Sharma
 
Basic quality concepts(3)
ngiyari
 
MySql slides (ppt)
webhostingguy
 
Open Source Package PHP & MySQL
kalaisai
 
PHP Project PPT
Pankil Agrawal
 
Best Practices - PHP and the Oracle Database
Christopher Jones
 
Impact of technology on education
Max Inder
 
Ad

Similar to working with PHP & DB's (20)

PPT
Migrating from PHP 4 to PHP 5
John Coggeshall
 
PPT
P H P Part I I, By Kian
phelios
 
PDF
Php summary
Michelle Darling
 
PPT
Download It
webhostingguy
 
PPT
Open Source Package Php Mysql 1228203701094763 9
isadorta
 
PPT
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
SenzotaSemakuwa
 
PPTX
Database Connectivity in PHP
Taha Malampatti
 
PPT
php databse handling
kunj desai
 
PPT
Php Data Objects
hiren.joshi
 
PPTX
Php and database functionality
Sayed Ahmed
 
PPTX
Php and database functionality
Sayed Ahmed
 
PPTX
PHP and database functionality
Sayed Ahmed
 
PDF
Php &amp; my sql - how do pdo, mysq-li, and x devapi do what they do
Dave Stokes
 
PPT
PHP MySQL
Md. Sirajus Salayhin
 
PPTX
PHP Database Programming Basics -- Northeast PHP
Dave Stokes
 
PPT
Mysql
guest817344
 
PPT
Quebec pdo
Valentine Dianov
 
Migrating from PHP 4 to PHP 5
John Coggeshall
 
P H P Part I I, By Kian
phelios
 
Php summary
Michelle Darling
 
Download It
webhostingguy
 
Open Source Package Php Mysql 1228203701094763 9
isadorta
 
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
SenzotaSemakuwa
 
Database Connectivity in PHP
Taha Malampatti
 
php databse handling
kunj desai
 
Php Data Objects
hiren.joshi
 
Php and database functionality
Sayed Ahmed
 
Php and database functionality
Sayed Ahmed
 
PHP and database functionality
Sayed Ahmed
 
Php &amp; my sql - how do pdo, mysq-li, and x devapi do what they do
Dave Stokes
 
PHP Database Programming Basics -- Northeast PHP
Dave Stokes
 
Quebec pdo
Valentine Dianov
 
Ad

Recently uploaded (20)

PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 

working with PHP & DB's

  • 2. Working With PHP And DBsIntroduction to PHP & DB
  • 5. The ORM Model & Interface
  • 6. Q & AIntroduction To PHP & DBFor many people, the main reason for learning PHP is because of the interaction with databases it can offer.
  • 7. It is surprising how useful a database can be when used with a website.
  • 8. There is a huge variety of things you can do when you interact the two, from displaying simple lists to running a complete website from a database. Why Would We Want A Database?Some examples of PHP and DBs being used together are:
  • 9. Banner Rotation - Each banner is generated by PHP script. This opens the DB and picks a random banner from it to show the visitor. It also counts the number of times the banner has been viewed.
  • 10. Forums- All the pages and messages in the forum are stored in the DB and are presented and updated by PHP scripts.Why Would We Want A Database?Some examples of PHP and DBs being used together cont’d:
  • 11. Databases – Storing user login and personal information, images, articles, item stock, sales data etc. All of these task can be done easily using PHP scripts.
  • 12. Reports – The most popular product on site, the best article, the biggest image. Visitor counters and trails, from which countries our visitors come from? All of these question can be answered easily using PHP scripts.PHP & SQL ServersSame Machine Same Network (LAN) Over The Internet (WAN) Internet(WAN)
  • 13. Supported Database TypesSome of the DBs that PHP supports:How Does PHP Use A Database?There are three major strategies for using a DB:
  • 14. The Native Interface – PHP connects directly to the SQL server using its native protocol, e.g. MySQL protocol version 10.
  • 15. The ODBC Interface – The ODBC driver is used as a mediator between the PHP and the SQL server. PHP uses the ODBC API which translates the SQL dialect.
  • 16. The ORM Interface – PHP uses objects which are mapped to DB tables and elements.Famous Sites That Use PHP & DB
  • 17. Working With PHP And DBsIntroduction to PHP & DB
  • 20. The ORM Model & Interface
  • 21. Q & A
  • 22. The Native InterfacePHP connects directly to the SQL server using its native protocol, e.g. MySQL protocol version 10.
  • 23. Pros: Best performance. No drivers or mediators are used, hence the connection and queries are performed in optimal speed.
  • 24. Cons: Compatibility. Each DB vendor has his own SQL dialect. Native MySQL code won’t run on ORACLE and vice versa.PHP MethodologySimple steps to follow:
  • 25. Create a connection to the database.
  • 27. Compose an SQL statement (query, creation etc).
  • 28. Submit the statement to the database.
  • 29. Receive results from the database.
  • 30. Parse results and use them.
  • 31. Close database connection. Repeat these steps for multiplestatements
  • 32. <?php$link = mysql_connect('localhost', 'root', '') or die('Could not connect: ' . mysql_error());mysql_select_db(dbname') or die('Could not select database');?>MySQL ConnectionPHP connects to the MySQL server:UsernameComputerPassword
  • 33. <?phpmysql_query("SET character_set_client = utf8");mysql_query("SET character_set_connection = utf8");mysql_query("SET character_set_results = utf8"); ?>MySQL UTF-8Working with UTF-8 (Hebrew).<?php$sql= "SELECT * FROM students WHERE ID > 5 order by id";$result = mysql_query($sql) or die ("Unable to SELECT FROM DB: ".$sql);while($line = mysql_fetch_array($result, MYSQL_ASSOC)){ echo $line["id"]."<br/>";}?>MySQL QueryPreparing, sending and receiving the query.MYSQL_ASSOC – Associative Array MYSQL_NUM – Numeric Array
  • 34. <?phpmysql_close($link);?>MySQL CloseClosing the connection (Very important).Working With PHP And DBsIntroduction to PHP & DB
  • 37. The ORM Model & Interface
  • 38. Q & AODBC Connectivity Diagram
  • 39. PHP & ODBCODBC - Open Database Connectivity provides a standard software API method for using database management systems (DBMS).
  • 40. In Windows, programming interfaces allow any application to talk to any printer or database by way of a “centralized manager”.
  • 41. The API that applications use on Windows to access the database "manager" is titled ODBC.ODBC InstallationODBC can be obtained for free at: http://dev.mysql.com/downloads/connector/odbc/5.1.html
  • 42. After a quick standard (next…next…) installation, make the following adjustments:
  • 43. Open the Administrative Tools icon in your Control Panel.
  • 44. Double-click on the Data Sources (ODBC) icon inside.
  • 45. Choose the System DSN tab and click on Add.
  • 46. Select the Microsoft Access Driver. Click Finish.
  • 47. In the next screen, click Select to locate the database.
  • 48. Give the database a Data Source Name (DSN).<?php$conn = odbc_connect('MySQL','user','password');....odbc_close($conn);?>PHP SQL ConnectThe odbc_connect() function is used for connecting to the database we configured in the ODBC driver.
  • 49. This function receives a database name (DSN), a user name and a password. It returns a database handle.Closing the connection
  • 50. <?php$conn=odbc_connect('MySQL','root','');if (!$conn) { exit("Connection Failed: " . $conn);}$sql="SELECT * FROM customer";?>PHP SQL QueryAfter the connection we create a String variable that holds the SQL Query:Error Handling
  • 51. <?php$rs= odbc_exec($conn,$sql);if (!$rs) {exit("Error in SQL");}while (odbc_fetch_row($rs)){echo odbc_result($rs,1);echo odbc_result($rs,2)."<br/>";}?>PHP SQL ResultsFirst we execute the query using odbc_exec().
  • 52. Second we use odbc_fetch_row() and odbc_result() to print the result to the user.Error Handling
  • 53. <?php$conn = odbc_connect('MySQL','root','');if (!$conn) {exit("Connection Failed: " . $conn);}$sql="SELECT * FROM customer";$rs= odbc_exec($conn,$sql);if (!$rs) {exit("Error in SQL");}while (odbc_fetch_row($rs)){echo odbc_result($rs,1);echo odbc_result($rs,2)."<br/>";}odbc_close($conn);?>Bringing it all together
  • 54. Working With PHP And DBsIntroduction to PHP & DB
  • 57. The ORM Model & Interface
  • 58. Q & AIntroduction To ORMObject Relational Mapping, is a database design approach that simplifies managing complex databases for programmers.
  • 59. The ORM layer in a PHP can make “objects” stored in a database behave like actual objects from a programming perspective.
  • 60. This way creating a new user would become very simple such as $user->new().MVC RecapThe user interacts with the user interface in some way. The controller handles the input event from the user interface, and converts the event into an appropriate user action, understandable for the model.The controller notifies the model of the user action, possibly resulting in a change in the model's state. A view queries the model in order to generate an appropriate user interface. The view gets its own data from the modelThe user interface waits for further user interactions, which restarts the control flow cycle.
  • 61. ORM ImplementationsBy abstracting actual database access, web development can be more productive and result in more reliable applications.
  • 62. ORM is very common among PHP frameworks, such as:<?phpclass Student extends DataMapper{public $has_many= array('course');public function __construct() { parent::__construct(); }}class Course extends DataMapper{public $has_many= array('student');public function __construct() { parent::__construct(); }}?>ORM Student ExampleModel classes for the student DB application.The classes represent entities which were defined in the DB.The classes could be given any relevant functionality.
  • 63. class Students extends Controller {public function __construct() {parent::__construct();$this->load->model('Student');$this->load->helper('url');$this->load->library('pagination'); }function index($offset=0) { $student_list= new Student();$total_rows= $student_list->count();$student_list->order_by('name'); $data['student_list'] = $student_list->get(5, $offset)->all; $config['base_url'] = site_url("students");$config['total_rows'] = $total_rows;$config['per_page'] = '5';$this->pagination->initialize($config); $this->load->view('student/index', $data); } }ORM Student ExampleController class for the students DB application.The class represents the functionality if the DB in queries.The classes could be given any relevant functionality.
  • 64. <table><tr><th>Name</th><th>Course</th></tr><?php$ctr= 0; ?><?phpforeach($student_listas $student): ?><?php$student->course->get()->order_by('name'); ?><?php$ctr++ ?><?phpif ($ctr% 2): ?><tr><td><?= $student->name ?></td><td><?foreach($student->course->all as $course): ?><?= $course->name ?><br/><?endforeach?></td></tr><?phpelse: ?><trclass="odd"><td> <?= $student->name ?></td><td> <?foreach($student->course->all as $course): ?><?= $course->name ?><br/><?endforeach?></td></tr><?phpendif; ?><?phpendforeach?></table>ORM Student ExampleViewer class for the students DB application.The class represents the UI that is presented to the user.The classes could be given any relevant design.
  • 65. Q & A