SlideShare uma empresa Scribd logo
1 de 23
Zend
Database
Buzoo PHP Lecture
By : Tya Herlina
Definition
Zend_Db and its related classes provide a
simple SQL database interface for Zend
Framework.
Zend_Db_Adapter
Zend_Db_Adapter is the basic class you use
to connect your PHP application to
an RDBMS. There is a different Adapter class
for each brand of RDBMS.
Zend_Db_Adapter (cont’d)
RDBMS

Adapter

IBM DB2

Pdo_ibm

MariaDB

Pdo_mysql

MySQL

Pdo_mysql

Microsoft SQL Server

Pdo_dblib

Oracle

Pdo_oci

PostgreSQL

Pdo_pgsql

SQLite

Pdo_sqlite
Set Connection
1.
2.
3.

Using a Zend_Db Adapter Constructor
Using the Zend_Db Factory
Using Zend_Config with the Zend_Db
Factory
1. Using a Zend_Db Adapter
Constructor
$db = new Zend_Db_Adapter_Pdo_Mysql(array(
’host’
=> ’buzoo.biz’,
’username’ => ’root’,
’password’ => ’’,
’dbname’
=> ’app_geshucloud’
));
2. Using the Zend_Db Factory
$db = Zend_Db::factory('Pdo_Mysql', array(
’host’
=> ’buzoo.biz’,
’username’ => ’root’,
’password’ => ’’,
’dbname’
=> ’app_geshucloud’
));
3. Using Zend_Config with the
Zend_Db Factory
database.host
database.username
database.password
database.dbname

=
=
=
=

“buzoo.biz“
“root“
“
“app_geshucloud“

$config = new Zend_Config_Ini(“path/to/config.ini“);
$db = Zend_Db::factory(‘Pdo_Mysql‘, $config->database);
Set Connection
Zend_Db_Table_Abstract::setDefaultAdapter
($db);

Get Connection
public function db() {
return Zend_Db_Table_Abstract::getDefaultAdapter();
}
Reading Query Results
1.
2.
3.
4.
5.
6.

Fetching a Complete Result Set
Fetching a Single Row from a Result Set
Fetching a Single Scalar from a Result Set
Fetching a Result Set as an Associative
Array
Fetching Key-Value Pairs from a Result
Set
Fetching a Single Column from a Result
Set
1. Fetching a Complete Result
Set
$models = $this->db()->fetchAll(
“SELECT * FROM `dtb_customer`”
);
print_r($models);
echo $models[0][`customerID`]; //44
Array (
[0] => Array (
[customerID]
[customerName]
[customerAddr]
[customerPhone]
[create_date]
[update_date]

=>
=>
=>
=>
=>
=>

44
Adisti Prihartini
Maleo 345 Bintan
2390554
2012-10-30 14:29:36
2012-11-27 16:04:45

[customerID]
[customerName]
[customerAddr]
[customerPhone]
[create_date]
[update_date]

=>
=>
=>
=>
=>
=>

45
Angela Nayoan
Van Heutz Boulevard 53 Batavia
2140
2012-10-30 14:29:36
2012-11-27 16:04:45

)
[1] => Array (

)
)
2. Fetching a Single Row from
a Result Set
$models = $this->db()->fetchRow(
“SELECT * FROM `dtb_customer` LIMIT 1”
);
print_r($models);
echo $models[`customerID`]; //44
Array (
[customerID]
[customerName]
[customerAddr]
[customerPhone]
[create_date]
[update_date]
)

=>
=>
=>
=>
=>
=>

44
Adisti Prihartini
Maleo 345 Bintan
2390554
2012-11-05 10:09:14
2012-11-21 10:35:45
3. Fetching a Single Scalar
from a Result Set
$models = $this->db()->fetchOne(
“SELECT `customerID` FROM `dtb_customer` LIMIT 1”
);
print_r($models);
echo $models[`customerID`];

44
Modifying Data to the
Database
1.
2.
3.

Inserting Data
Updating Data
Deleting Data
1. Inserting Data
$this->db()->insert(‘dtb_room_facility‘, array(
‘room_id‘
=> 99,
‘facility_id‘ => 99
));
echo $this->db()->lastInsertId(); //5
$model = new Dao_RoomFacility();
$new_id = $model->insert(array(
‘room_id‘
=> 99,
‘facility_id‘
=> 99
));
echo $new_id; //5
2. Updating Data
$update_id = $this->db()->update('dtb_room_facility',
array(
'room_id'
=> 999,
'facility_id' => 999
), 'id = 999');
echo $update_id; //1

$model = new Dao_RoomFacility();
$update_id = $model->update(
array(
'room_id'
=> 899,
'facility_id' => 899
), 'id = 899');
echo $update_id; //1
3. Deleting Data
$delete_id = $this->db()->delete(
'`dtb_room_facility`',
'`id` = 999'
);
echo $delete_id; //1

$model = new Dao_RoomFacility();
$delete_id = $model->delete(
'`id` = 899');
echo $delete_id; //1
Preventing SQL Injection
$name = "O'Reilly";
$sql =
"SELECT * FROM `dtb_customer` WHERE
`customerName` = '$name'";

echo $sql;
// SELECT * FROM `dtb_customer` WHERE `customerName`
= 'O'Reilly'
Quoting Values and Identifiers
1.
2.
3.

Using quote()
Using quoteInto()
Using quoteIdentifier()
1. Using quote()
$name = $this->db()->quote("O'Reilly");
$sql =
"SELECT * FROM `dtb_customer` WHERE `customerName` =
$name";

echo $sql;
// SELECT * FROM `dtb_customer` WHERE `customerName` = 'O'Reilly'

$phone = $this->db()->quote("1234", "INTEGER");
$sql =
"SELECT * FROM `dtb_customer` WHERE
`customerPhone` = $phone";

echo $sql;
// SELECT * FROM `dtb_customer` WHERE `customerPhone` = 1234
2. Using quoteInto()
$name = "O'Reilly";
$sql = $this->db()->quoteInto(
"SELECT * FROM `dtb_customer`
WHERE `customerName` = ?", $name
);
echo $sql;
// SELECT * FROM `dtb_customer` WHERE `customerName` = 'O'Reilly'
Notes
 Always

store your logic query in
Models/Logic/your_logic.php
 Minimizing the possibility of SQL injection
with quoting values
 When creating logic, please reduce the
possibility of errors
 Always return your logic result value
 Always check the existing logic before
you make yours
Thank you~
 Question?
 Share?
 Critics?
 Advice?

Mais conteúdo relacionado

Mais procurados

Managing a shared_mysql_farm_phpday2011
Managing a shared_mysql_farm_phpday2011Managing a shared_mysql_farm_phpday2011
Managing a shared_mysql_farm_phpday2011
Combell NV
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
Night Sailer
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Luis Curo Salvatierra
 
MTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new APIMTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new API
Six Apart KK
 
CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)
brian d foy
 

Mais procurados (20)

[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
 
Managing a shared_mysql_farm_phpday2011
Managing a shared_mysql_farm_phpday2011Managing a shared_mysql_farm_phpday2011
Managing a shared_mysql_farm_phpday2011
 
I regret nothing
I regret nothingI regret nothing
I regret nothing
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in Drupal
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Drupal Module Development
Drupal Module DevelopmentDrupal Module Development
Drupal Module Development
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
 
Presentation1
Presentation1Presentation1
Presentation1
 
MTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new APIMTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new API
 
How to write bad code in redux (ReactNext 2018)
How to write bad code in redux (ReactNext 2018)How to write bad code in redux (ReactNext 2018)
How to write bad code in redux (ReactNext 2018)
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
 
CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)
 

Destaque

Destaque (8)

Sales Methodologies - A quick guide to boosting success - realSociable
Sales Methodologies - A quick guide to boosting success - realSociableSales Methodologies - A quick guide to boosting success - realSociable
Sales Methodologies - A quick guide to boosting success - realSociable
 
Design Pattern with Burger
Design Pattern with BurgerDesign Pattern with Burger
Design Pattern with Burger
 
NextGen Customer Engagement - An Extension from Dave McClure's Pirate Startup...
NextGen Customer Engagement - An Extension from Dave McClure's Pirate Startup...NextGen Customer Engagement - An Extension from Dave McClure's Pirate Startup...
NextGen Customer Engagement - An Extension from Dave McClure's Pirate Startup...
 
Slicing Up the Mobile Services Revenue Pie
Slicing Up the Mobile Services Revenue PieSlicing Up the Mobile Services Revenue Pie
Slicing Up the Mobile Services Revenue Pie
 
realSociable - Creating a need and changing sales flow
realSociable - Creating a need and changing sales flowrealSociable - Creating a need and changing sales flow
realSociable - Creating a need and changing sales flow
 
Piling lica
Piling licaPiling lica
Piling lica
 
Engagement for a Modern Sales Team
Engagement for a Modern Sales TeamEngagement for a Modern Sales Team
Engagement for a Modern Sales Team
 
The beatles
The beatlesThe beatles
The beatles
 

Semelhante a [PHP] Zend_Db (Zend Framework)

Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)
Pavel Novitsky
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
webhostingguy
 

Semelhante a [PHP] Zend_Db (Zend Framework) (20)

ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
 
Code Igniter 2
Code Igniter 2Code Igniter 2
Code Igniter 2
 
8. vederea inregistrarilor
8. vederea inregistrarilor8. vederea inregistrarilor
8. vederea inregistrarilor
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
Zend Framework 2 - Basic Components
Zend Framework 2  - Basic ComponentsZend Framework 2  - Basic Components
Zend Framework 2 - Basic Components
 
Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
 
Part 2
Part 2Part 2
Part 2
 
Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2
 
Disregard Inputs, Acquire Zend_Form
Disregard Inputs, Acquire Zend_FormDisregard Inputs, Acquire Zend_Form
Disregard Inputs, Acquire Zend_Form
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Zend Framework
Zend FrameworkZend Framework
Zend Framework
 
15. CodeIgniter editarea inregistrarilor
15. CodeIgniter editarea inregistrarilor15. CodeIgniter editarea inregistrarilor
15. CodeIgniter editarea inregistrarilor
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioning
 
Working with databases
Working with databasesWorking with databases
Working with databases
 
19. CodeIgniter imagini in mysql
19. CodeIgniter imagini in mysql19. CodeIgniter imagini in mysql
19. CodeIgniter imagini in mysql
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_Tool
 
About Data::ObjectDriver
About Data::ObjectDriverAbout Data::ObjectDriver
About Data::ObjectDriver
 
Drupal Module Development - OSI Days 2010
Drupal Module Development - OSI Days 2010Drupal Module Development - OSI Days 2010
Drupal Module Development - OSI Days 2010
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

[PHP] Zend_Db (Zend Framework)

  • 2. Definition Zend_Db and its related classes provide a simple SQL database interface for Zend Framework.
  • 3. Zend_Db_Adapter Zend_Db_Adapter is the basic class you use to connect your PHP application to an RDBMS. There is a different Adapter class for each brand of RDBMS.
  • 4. Zend_Db_Adapter (cont’d) RDBMS Adapter IBM DB2 Pdo_ibm MariaDB Pdo_mysql MySQL Pdo_mysql Microsoft SQL Server Pdo_dblib Oracle Pdo_oci PostgreSQL Pdo_pgsql SQLite Pdo_sqlite
  • 5. Set Connection 1. 2. 3. Using a Zend_Db Adapter Constructor Using the Zend_Db Factory Using Zend_Config with the Zend_Db Factory
  • 6. 1. Using a Zend_Db Adapter Constructor $db = new Zend_Db_Adapter_Pdo_Mysql(array( ’host’ => ’buzoo.biz’, ’username’ => ’root’, ’password’ => ’’, ’dbname’ => ’app_geshucloud’ ));
  • 7. 2. Using the Zend_Db Factory $db = Zend_Db::factory('Pdo_Mysql', array( ’host’ => ’buzoo.biz’, ’username’ => ’root’, ’password’ => ’’, ’dbname’ => ’app_geshucloud’ ));
  • 8. 3. Using Zend_Config with the Zend_Db Factory database.host database.username database.password database.dbname = = = = “buzoo.biz“ “root“ “ “app_geshucloud“ $config = new Zend_Config_Ini(“path/to/config.ini“); $db = Zend_Db::factory(‘Pdo_Mysql‘, $config->database);
  • 9. Set Connection Zend_Db_Table_Abstract::setDefaultAdapter ($db); Get Connection public function db() { return Zend_Db_Table_Abstract::getDefaultAdapter(); }
  • 10. Reading Query Results 1. 2. 3. 4. 5. 6. Fetching a Complete Result Set Fetching a Single Row from a Result Set Fetching a Single Scalar from a Result Set Fetching a Result Set as an Associative Array Fetching Key-Value Pairs from a Result Set Fetching a Single Column from a Result Set
  • 11. 1. Fetching a Complete Result Set $models = $this->db()->fetchAll( “SELECT * FROM `dtb_customer`” ); print_r($models); echo $models[0][`customerID`]; //44 Array ( [0] => Array ( [customerID] [customerName] [customerAddr] [customerPhone] [create_date] [update_date] => => => => => => 44 Adisti Prihartini Maleo 345 Bintan 2390554 2012-10-30 14:29:36 2012-11-27 16:04:45 [customerID] [customerName] [customerAddr] [customerPhone] [create_date] [update_date] => => => => => => 45 Angela Nayoan Van Heutz Boulevard 53 Batavia 2140 2012-10-30 14:29:36 2012-11-27 16:04:45 ) [1] => Array ( ) )
  • 12. 2. Fetching a Single Row from a Result Set $models = $this->db()->fetchRow( “SELECT * FROM `dtb_customer` LIMIT 1” ); print_r($models); echo $models[`customerID`]; //44 Array ( [customerID] [customerName] [customerAddr] [customerPhone] [create_date] [update_date] ) => => => => => => 44 Adisti Prihartini Maleo 345 Bintan 2390554 2012-11-05 10:09:14 2012-11-21 10:35:45
  • 13. 3. Fetching a Single Scalar from a Result Set $models = $this->db()->fetchOne( “SELECT `customerID` FROM `dtb_customer` LIMIT 1” ); print_r($models); echo $models[`customerID`]; 44
  • 14. Modifying Data to the Database 1. 2. 3. Inserting Data Updating Data Deleting Data
  • 15. 1. Inserting Data $this->db()->insert(‘dtb_room_facility‘, array( ‘room_id‘ => 99, ‘facility_id‘ => 99 )); echo $this->db()->lastInsertId(); //5 $model = new Dao_RoomFacility(); $new_id = $model->insert(array( ‘room_id‘ => 99, ‘facility_id‘ => 99 )); echo $new_id; //5
  • 16. 2. Updating Data $update_id = $this->db()->update('dtb_room_facility', array( 'room_id' => 999, 'facility_id' => 999 ), 'id = 999'); echo $update_id; //1 $model = new Dao_RoomFacility(); $update_id = $model->update( array( 'room_id' => 899, 'facility_id' => 899 ), 'id = 899'); echo $update_id; //1
  • 17. 3. Deleting Data $delete_id = $this->db()->delete( '`dtb_room_facility`', '`id` = 999' ); echo $delete_id; //1 $model = new Dao_RoomFacility(); $delete_id = $model->delete( '`id` = 899'); echo $delete_id; //1
  • 18. Preventing SQL Injection $name = "O'Reilly"; $sql = "SELECT * FROM `dtb_customer` WHERE `customerName` = '$name'"; echo $sql; // SELECT * FROM `dtb_customer` WHERE `customerName` = 'O'Reilly'
  • 19. Quoting Values and Identifiers 1. 2. 3. Using quote() Using quoteInto() Using quoteIdentifier()
  • 20. 1. Using quote() $name = $this->db()->quote("O'Reilly"); $sql = "SELECT * FROM `dtb_customer` WHERE `customerName` = $name"; echo $sql; // SELECT * FROM `dtb_customer` WHERE `customerName` = 'O'Reilly' $phone = $this->db()->quote("1234", "INTEGER"); $sql = "SELECT * FROM `dtb_customer` WHERE `customerPhone` = $phone"; echo $sql; // SELECT * FROM `dtb_customer` WHERE `customerPhone` = 1234
  • 21. 2. Using quoteInto() $name = "O'Reilly"; $sql = $this->db()->quoteInto( "SELECT * FROM `dtb_customer` WHERE `customerName` = ?", $name ); echo $sql; // SELECT * FROM `dtb_customer` WHERE `customerName` = 'O'Reilly'
  • 22. Notes  Always store your logic query in Models/Logic/your_logic.php  Minimizing the possibility of SQL injection with quoting values  When creating logic, please reduce the possibility of errors  Always return your logic result value  Always check the existing logic before you make yours
  • 23. Thank you~  Question?  Share?  Critics?  Advice?