SlideShare a Scribd company logo
Chapter
MySQL Database Connection
 Opening Database Connection
 PHP provides mysql_connect() function to open a database connection.
 This function takes five parameters and returns a MySQL link identifier on success, or
FALSE on failure.
Syntax: connection mysql_connect(server,user,passwd,new_link,client_flag);
Cont’d
Cont’d
Cont’d
 NOTE − You can specify server, user, passwd in php.ini file instead of using them again and
again in your every PHP scripts. Check php.ini file configuration.
 Closing Database Connection
 PHP provides the simplest function mysql_close() to close a database connection.
 This function takes connection resource returned by mysql_connect() function.
 It returns TRUE on success or FALSE on failure.
Syntax: bool mysql_close ( resource $link_identifier );
If a resource is not specified then last opend database connection will be closed.
Example
Try out following example to open and close a database connection −
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
} else
echo 'Connected successfully';
mysql_close($conn); ?>
Cont’d
Cont’d
Try out following example to create a database −
<?php
$dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) { die('Could not connect: ' . mysql_error()); }
echo 'Connected successfully';
$sql = 'CREATE Database test_db';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create database: ' . mysql_error());
} echo "Database test_db created successfullyn";
mysql_close($conn); ?>
Cont’d
 Selecting a Database
 Once you establish a connection with a database server then it is required to select a
particular database where all your tables are associated.
 This is required because there may be multiple databases residing on a single server and you
can do work with a single database at a time.
 PHP provides function mysql_select_db to select a database. It returns TRUE on success or
FALSE on failure.
Syntax: bool mysql_select_db( db_name, connection );
Cont’d
Example
Here is the example showing you how to select a database.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) { die('Could not connect: ' . mysql_error()); }
echo 'Connected successfully';
mysql_select_db( 'test_db' );
mysql_close($conn); ?>
Creating Database Tables
 To create tables in the new database you need to do the same thing as creating the database.
 First create the SQL query to create the tables then execute the query using mysql_query() function.
Example
 Try out following example to create a table −
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) { die('Could not connect: ' . mysql_error()); }
echo 'Connected successfully';
Cont’d
$sql = 'CREATE TABLE employee( '.
'emp_id INT NOT NULL AUTO_INCREMENT, '.
'emp_name VARCHAR(20) NOT NULL, '.
'emp_address VARCHAR(20) NOT NULL, '.
'emp_salary INT NOT NULL, '.
'join_date timestamp(14) NOT NULL, '.
'primary key ( emp_id ))';
mysql_select_db(‘testdatabase');
$retval = mysql_query( $sql, $conn );
if(! $retval ) { die('Could not create table: ' . mysql_error()); }
echo "Table employee created successfullyn";
mysql_close($conn); ?>
Cont’d
 In case you need to create many tables then its better to create a text file first and put all the SQL
commands in that text file and then load that file into $sql variable and excute those commands.
 Consider the following content in sql_query.txt file
CREATE TABLE employee(
emp_id INT NOT NULL AUTO_INCREMENT,
emp_name VARCHAR(20) NOT NULL,
emp_address VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL,
join_date timestamp(14) NOT NULL,
primary key ( emp_id ));
Cont’d
<?php
$dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) { die('Could not connect: ' . mysql_error()); }
$query_file = 'sql_query.txt';
$fp = fopen($query_file, 'r');
$sql = fread($fp, filesize($query_file));
fclose($fp);
mysql_select_db(‘testdatabase');
$retval = mysql_query( $sql, $conn );
if(! $retval ) { die('Could not create table: ' . mysql_error()); }
echo "Table employee created successfullyn";
mysql_close($conn); ?>
Deleting MySQL Database Using PHP
 Deleting a Database
 If a database is no longer required then it can be deleted forever.
 You can pass an SQL command to mysql_query to delete a database.
Example
Try out following example to drop a database.
Cont’d
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) { die('Could not connect: ' . mysql_error()); }
$sql = 'DROP DATABASE test_db';
$retval = mysql_query( $sql, $conn );
if(! $retval ) { die('Could not delete database db_test: ' . mysql_error()); }
echo "Database deleted successfullyn";
mysql_close($conn); ?>
Deleting a Table
 Its again a matter of issuing one SQL command through mysql_query function to delete any
database table. But be very careful while using this command because by doing so you can
delete some important information you have in your table.
Example
Try out following example to drop a table −
Cont’d
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) { die('Could not connect: ' . mysql_error()); }
$sql = 'DROP TABLE employee';
$retval = mysql_query( $sql, $conn );
if(! $retval ) { die('Could not delete table employee: ' . mysql_error()); }
echo "Table deleted successfullyn";
mysql_close($conn); ?>
Insert Data into MySQL Database
 Data can be entered into MySQL tables by executing SQL INSERT statement through PHP function mysql_query.
Below a simple example to insert a record into employee table.
<?php
$conn = mysql_connect(localhost:3036', ‘root’, ‘rotpassword’);
if(! $conn ) { die('Could not connect: ' . mysql_error()); }
$sql = 'INSERT INTO employee '. '(emp_name, emp_address, emp_salary, join_date) '. 'VALUES ( "guest", "XYZ",
2000, NOW() )';
mysql_select_db(testdatabase');
$retval = mysql_query( $sql, $conn );
if(! $retval ) { die('Could not enter data: ' . mysql_error()); }
echo "data Entered successfullyn";
mysql_close($conn); ?>
Cont’d
 In real application, all the values will be taken using HTML form and then those values will
be captured using PHP script and finally they will be inserted into MySQL tables.
 While doing data insert its best practice to use function get_magic_quotes_gpc() to check if
current configuration for magic quote is set or not.
 If this function returns false then use function addslashes() to add slashes before quotes.
Example check out add_employee.php file
Ad

More Related Content

Similar to chapter_Seven Database manipulation using php.pptx (20)

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
Dhivyaa C.R
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
okelloerick
 
Connecting_to_Database(MySQL)_in_PHP.pptx
Connecting_to_Database(MySQL)_in_PHP.pptxConnecting_to_Database(MySQL)_in_PHP.pptx
Connecting_to_Database(MySQL)_in_PHP.pptx
TempMail233488
 
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
moirarandell
 
Mysql & Php
Mysql & PhpMysql & Php
Mysql & Php
Inbal Geffen
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
Jeremy Kendall
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Rifat Nabi
 
DBD::SQLite
DBD::SQLiteDBD::SQLite
DBD::SQLite
charsbar
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
salissal
 
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
saritasingh19866
 
veracruz
veracruzveracruz
veracruz
tutorialsruby
 
veracruz
veracruzveracruz
veracruz
tutorialsruby
 
veracruz
veracruzveracruz
veracruz
tutorialsruby
 
veracruz
veracruzveracruz
veracruz
tutorialsruby
 
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
 
Database presentation
Database presentationDatabase presentation
Database presentation
webhostingguy
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
wahidullah mudaser
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
Computer Hardware & Trouble shooting
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For Beginners
Priti Solanki
 
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
Dhivyaa C.R
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
okelloerick
 
Connecting_to_Database(MySQL)_in_PHP.pptx
Connecting_to_Database(MySQL)_in_PHP.pptxConnecting_to_Database(MySQL)_in_PHP.pptx
Connecting_to_Database(MySQL)_in_PHP.pptx
TempMail233488
 
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
moirarandell
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Rifat Nabi
 
DBD::SQLite
DBD::SQLiteDBD::SQLite
DBD::SQLite
charsbar
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
salissal
 
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
saritasingh19866
 
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
 
Database presentation
Database presentationDatabase presentation
Database presentation
webhostingguy
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For Beginners
Priti Solanki
 

More from Getawu (7)

5 Protect-Application-or-System-Software (2).pptx
5 Protect-Application-or-System-Software (2).pptx5 Protect-Application-or-System-Software (2).pptx
5 Protect-Application-or-System-Software (2).pptx
Getawu
 
moniteradministratornetworksystemsecurity-231020035832-51b6b47f (1).pdf
moniteradministratornetworksystemsecurity-231020035832-51b6b47f (1).pdfmoniteradministratornetworksystemsecurity-231020035832-51b6b47f (1).pdf
moniteradministratornetworksystemsecurity-231020035832-51b6b47f (1).pdf
Getawu
 
Develop Keyboard Skill.pptx er power point
Develop Keyboard Skill.pptx er power pointDevelop Keyboard Skill.pptx er power point
Develop Keyboard Skill.pptx er power point
Getawu
 
Identifying and categorizing computer software
Identifying and categorizing computer softwareIdentifying and categorizing computer software
Identifying and categorizing computer software
Getawu
 
: Connect hardware peripherals Part one
:   Connect hardware peripherals Part one:   Connect hardware peripherals Part one
: Connect hardware peripherals Part one
Getawu
 
Connect a workstation to the internet ppt
Connect a workstation to the internet pptConnect a workstation to the internet ppt
Connect a workstation to the internet ppt
Getawu
 
Hardware and Networking Service Document PPT
Hardware and Networking Service Document PPTHardware and Networking Service Document PPT
Hardware and Networking Service Document PPT
Getawu
 
5 Protect-Application-or-System-Software (2).pptx
5 Protect-Application-or-System-Software (2).pptx5 Protect-Application-or-System-Software (2).pptx
5 Protect-Application-or-System-Software (2).pptx
Getawu
 
moniteradministratornetworksystemsecurity-231020035832-51b6b47f (1).pdf
moniteradministratornetworksystemsecurity-231020035832-51b6b47f (1).pdfmoniteradministratornetworksystemsecurity-231020035832-51b6b47f (1).pdf
moniteradministratornetworksystemsecurity-231020035832-51b6b47f (1).pdf
Getawu
 
Develop Keyboard Skill.pptx er power point
Develop Keyboard Skill.pptx er power pointDevelop Keyboard Skill.pptx er power point
Develop Keyboard Skill.pptx er power point
Getawu
 
Identifying and categorizing computer software
Identifying and categorizing computer softwareIdentifying and categorizing computer software
Identifying and categorizing computer software
Getawu
 
: Connect hardware peripherals Part one
:   Connect hardware peripherals Part one:   Connect hardware peripherals Part one
: Connect hardware peripherals Part one
Getawu
 
Connect a workstation to the internet ppt
Connect a workstation to the internet pptConnect a workstation to the internet ppt
Connect a workstation to the internet ppt
Getawu
 
Hardware and Networking Service Document PPT
Hardware and Networking Service Document PPTHardware and Networking Service Document PPT
Hardware and Networking Service Document PPT
Getawu
 
Ad

Recently uploaded (20)

Cryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptxCryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptx
riyageorge2024
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...
FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...
FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...
Lionel Briand
 
Foundation Models for Time Series : A Survey
Foundation Models for Time Series : A SurveyFoundation Models for Time Series : A Survey
Foundation Models for Time Series : A Survey
jayanthkalyanam1
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Implementing promises with typescripts, step by step
Implementing promises with typescripts, step by stepImplementing promises with typescripts, step by step
Implementing promises with typescripts, step by step
Ran Wahle
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
Imma Valls Bernaus
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Cryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptxCryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptx
riyageorge2024
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...
FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...
FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...
Lionel Briand
 
Foundation Models for Time Series : A Survey
Foundation Models for Time Series : A SurveyFoundation Models for Time Series : A Survey
Foundation Models for Time Series : A Survey
jayanthkalyanam1
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Implementing promises with typescripts, step by step
Implementing promises with typescripts, step by stepImplementing promises with typescripts, step by step
Implementing promises with typescripts, step by step
Ran Wahle
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
Imma Valls Bernaus
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Ad

chapter_Seven Database manipulation using php.pptx

  • 2. MySQL Database Connection  Opening Database Connection  PHP provides mysql_connect() function to open a database connection.  This function takes five parameters and returns a MySQL link identifier on success, or FALSE on failure. Syntax: connection mysql_connect(server,user,passwd,new_link,client_flag);
  • 5. Cont’d  NOTE − You can specify server, user, passwd in php.ini file instead of using them again and again in your every PHP scripts. Check php.ini file configuration.  Closing Database Connection  PHP provides the simplest function mysql_close() to close a database connection.  This function takes connection resource returned by mysql_connect() function.  It returns TRUE on success or FALSE on failure. Syntax: bool mysql_close ( resource $link_identifier ); If a resource is not specified then last opend database connection will be closed.
  • 6. Example Try out following example to open and close a database connection − <?php $dbhost = 'localhost:3036'; $dbuser = 'guest'; $dbpass = 'guest123'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } else echo 'Connected successfully'; mysql_close($conn); ?>
  • 8. Cont’d Try out following example to create a database − <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; $sql = 'CREATE Database test_db'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not create database: ' . mysql_error()); } echo "Database test_db created successfullyn"; mysql_close($conn); ?>
  • 9. Cont’d  Selecting a Database  Once you establish a connection with a database server then it is required to select a particular database where all your tables are associated.  This is required because there may be multiple databases residing on a single server and you can do work with a single database at a time.  PHP provides function mysql_select_db to select a database. It returns TRUE on success or FALSE on failure. Syntax: bool mysql_select_db( db_name, connection );
  • 11. Example Here is the example showing you how to select a database. <?php $dbhost = 'localhost:3036'; $dbuser = 'guest'; $dbpass = 'guest123'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_select_db( 'test_db' ); mysql_close($conn); ?>
  • 12. Creating Database Tables  To create tables in the new database you need to do the same thing as creating the database.  First create the SQL query to create the tables then execute the query using mysql_query() function. Example  Try out following example to create a table − <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully';
  • 13. Cont’d $sql = 'CREATE TABLE employee( '. 'emp_id INT NOT NULL AUTO_INCREMENT, '. 'emp_name VARCHAR(20) NOT NULL, '. 'emp_address VARCHAR(20) NOT NULL, '. 'emp_salary INT NOT NULL, '. 'join_date timestamp(14) NOT NULL, '. 'primary key ( emp_id ))'; mysql_select_db(‘testdatabase'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not create table: ' . mysql_error()); } echo "Table employee created successfullyn"; mysql_close($conn); ?>
  • 14. Cont’d  In case you need to create many tables then its better to create a text file first and put all the SQL commands in that text file and then load that file into $sql variable and excute those commands.  Consider the following content in sql_query.txt file CREATE TABLE employee( emp_id INT NOT NULL AUTO_INCREMENT, emp_name VARCHAR(20) NOT NULL, emp_address VARCHAR(20) NOT NULL, emp_salary INT NOT NULL, join_date timestamp(14) NOT NULL, primary key ( emp_id ));
  • 15. Cont’d <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $query_file = 'sql_query.txt'; $fp = fopen($query_file, 'r'); $sql = fread($fp, filesize($query_file)); fclose($fp); mysql_select_db(‘testdatabase'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not create table: ' . mysql_error()); } echo "Table employee created successfullyn"; mysql_close($conn); ?>
  • 16. Deleting MySQL Database Using PHP  Deleting a Database  If a database is no longer required then it can be deleted forever.  You can pass an SQL command to mysql_query to delete a database. Example Try out following example to drop a database.
  • 17. Cont’d <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'DROP DATABASE test_db'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete database db_test: ' . mysql_error()); } echo "Database deleted successfullyn"; mysql_close($conn); ?>
  • 18. Deleting a Table  Its again a matter of issuing one SQL command through mysql_query function to delete any database table. But be very careful while using this command because by doing so you can delete some important information you have in your table. Example Try out following example to drop a table −
  • 19. Cont’d <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'DROP TABLE employee'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete table employee: ' . mysql_error()); } echo "Table deleted successfullyn"; mysql_close($conn); ?>
  • 20. Insert Data into MySQL Database  Data can be entered into MySQL tables by executing SQL INSERT statement through PHP function mysql_query. Below a simple example to insert a record into employee table. <?php $conn = mysql_connect(localhost:3036', ‘root’, ‘rotpassword’); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'INSERT INTO employee '. '(emp_name, emp_address, emp_salary, join_date) '. 'VALUES ( "guest", "XYZ", 2000, NOW() )'; mysql_select_db(testdatabase'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } echo "data Entered successfullyn"; mysql_close($conn); ?>
  • 21. Cont’d  In real application, all the values will be taken using HTML form and then those values will be captured using PHP script and finally they will be inserted into MySQL tables.  While doing data insert its best practice to use function get_magic_quotes_gpc() to check if current configuration for magic quote is set or not.  If this function returns false then use function addslashes() to add slashes before quotes. Example check out add_employee.php file