SlideShare uma empresa Scribd logo
1 de 13
Baixar para ler offline
Connecting to MySQL
           and Selecting the
           Database

  Pengaturcaraan PHP




Pengaturcaraan PHP

The first step when dealing with the MySQL client and connecting to the
server requires the appropriately named mysql_connect() function:




                                                                          1
Pengaturcaraan PHP
Once you have connected to MySQL, you will need to select the database
with which you want to work. This is the equivalent of saying USE
databasename within the mysql client and is accomplished with the
mysql_select_ db() function:




Let's start the demonstration of connecting to MySQL by creating a special
file just for that purpose. Other PHP scripts that require a MySQL connection
can include this file. We'll also make use of the mysql_error() function.




Pengaturcaraan PHP

To connect to and select a database, first create a new PHP document in
your text editor, mysql_connect.php.

Connect PHP with mySQL
<?
$dbhost = "localhost";
$dbname = “pentadbiran";
$dbuser = “admin";
$dbpass = “123456";

mysql_connect("$dbhost","$dbuser","$dbpass");

@mysql_select_db($dbname) or die( "Unable to select database");

?>




                                                                                2
Pengaturcaraan PHP
Since this file contains information that
must be kept private, we'll use a .php
extension. By doing so, even if
malicious users ran this script in their
Web browser, they would not see the
page's actual content. Be sure to save
the file as mysql_connect.php.

Upload the file to your server, outside
of the Web document root. Because
the file contains sensitive MySQL
access information, it ought to be
stored securely. If you can, place it in
the directory immediately above, or
otherwise outside, of the Web
directory. This way the file will not be
accessible from a Web browser.




Pengaturcaraan PHP
Temporarily place a copy of the
script within the Web document
root and run the script in your Web
browser. In order to test the script,
you'll want to place a copy on the
server so that it's accessible from
the Web browser (which means it
must be in the Web directory).

If the script works properly, the
result should be a blank page. If
you see an "Access denied..." or
similar message, it means that the
combination of username,
password, and host does not have
permission to access the particular
database.




                                            3
Executing Simple
         Queries


Pengaturcaraan PHP




Pengaturcaraan PHP
  The following is a simple PHP function for executing a query:




For simple queries like INSERT, UPDATE, DELETE, etc. (which do not
return records), the $result variable will be either TRUE or FALSE
depending upon whether the query executed successfully. For complex
queries that do return records (SELECT, SHOW, DESCRIBE, CREATE,
and EXPLAIN), the $result variable will be a resource link to the results
of the query if it worked, or be FALSE if it did not.




                                                                            4
Pengaturcaraan PHP

Retrieve data with mySQL+PHP

Example :

$query="SELECT * FROM member where nokp=‘123456'";
$result=mysql_query($query);
while ($myrow = mysql_fetch_array($result))
{
    $id=$myrow["id"];
    $login=$myrow["login"];
    print “$id - $login<br>”;
}




Pengaturcaraan PHP
Retrieve data with mySQL+PHP

Contoh :

$query="SELECT * FROM member where nokp=‘$nokp’";
$result=mysql_query($query);
while ($myrow = mysql_fetch_rows($result))
{
             $id=$myrow[0];
             $login=$myrow[1];
}
print “$id - $login”;




                                                     5
Pengaturcaraan PHP
One final, albeit optional, step in your script would be to close the existing
MySQL connection once you're finished with it:




This function is not required, because PHP will automatically close the
connection at the end of a script, but it does make for good programming
form to incorporate it.




            Retrieving Query
            Results


  Pengaturcaraan PHP




                                                                                 6
Pengaturcaraan PHP
The primary tool for handling SELECT query results is mysql_fetch_array(),
which takes the query result variable and returns one row of data at a time in
an array format. You'll want to use this function within a loop that will continue
to access every returned row as long as there are more to be read.

The mysql_fetch_array() function takes an optional parameter specifying what
type of array is returned: associative, indexed, or both. An associative array
allows you to refer to column values by name, whereas an indexed array
requires you to use only numbers (starting at 0 for the first column returned).




Pengaturcaraan PHP
Each parameter is defined by a constant. The MYSQL_NUM setting is
marginally faster (and uses less memory) than the other options. Conversely,
MYSQL_ASSOC is more specific ($row['column'] rather than $row[3]) and will
continue to work even if the table structure or query changes.

The table below lists the basic construction for reading every record from a
query. Adding one of these constants as an optional parameter to the
mysql_fetch_array() function dictates how you can access the values returned.
The default setting of the function is MYSQL_BOTH.

          Constant                   Example
          MYSQL_ASSOC                $row[0] or $row['column']
          MYSQL_NUM                  $row[0]
          MYSQL_BOTH                 $row['column']




                                                                                     7
Pengaturcaraan PHP
An optional step you can take when using mysql_fetch_array() would be
to free up the query result resources once you are done using them:




           Counting Returned
           Records


  Pengaturcaraan PHP




                                                                        8
Pengaturcaraan PHP

 The logical function mysql_num_rows()returns the number of
 rows retrieved by a SELECT query, taking the query result as
 a parameter.




Pengaturcaraan PHP

Count data with mysql+PHP

Example :

$names = mysql_query("SELECT * FROM member WHERE login='$login'");
$num = mysql_num_rows($names);

Or

$total_results = mysql_result(mysql_query("SELECT COUNT(*) as Num FROM
member where login=‘$login'"),0);
$total_pages = ceil($total_results);




                                                                         9
Updating Records with
       PHP


 Pengaturcaraan PHP




Pengaturcaraan PHP

Update (single data) with mySQL+PHP

Contoh :

mysql_db_query($dbname, “update table set
nama=“ahmad” where nokp=‘123456'");

Or

mysql_db_query($dbname, “update table set
nama=“$nama” where nokp=‘$nokp'");




                                            10
Pengaturcaraan PHP

Update (multiple data) with mySQL+PHP

Example :

mysql_db_query($dbname, “update table set
nama=“ahmad”, jantina=“lelaki” where nokp=‘123456'");

Or

mysql_db_query($dbname, “update table set
nama=“$nama”, jantina=‘$jantina’ where nokp=‘$nokp'");




        Inserting Records



  Pengaturcaraan PHP




                                                         11
Pengaturcaraan PHP

Insert data with mySQL+PHP

Example

mysql_db_query($dbname, "insert into $table values
('','$nama','$nokp','$jantina')");

Or

mysql_db_query($dbname, "insert into members
values ('','$nama','$nokp','$jantina')");




        Deleting Records



 Pengaturcaraan PHP




                                                     12
Pengaturcaraan PHP

Delete Record with mySQL+PHP

Example :

mysql_db_query($dbname, "delete from $table where
nama=‘ahmad'");

Or

mysql_db_query($dbname, "delete from $table where
nama=‘$nama'");




       End



 Pengaturcaraan PHP




                                                    13

Mais conteúdo relacionado

Mais procurados (17)

Php Mysql
Php Mysql Php Mysql
Php Mysql
 
Mysql & Php
Mysql & PhpMysql & Php
Mysql & Php
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With Mysql
 
Php mysq
Php mysqPhp mysq
Php mysq
 
lab56_db
lab56_dblab56_db
lab56_db
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
 
Php verses my sql
Php verses my sqlPhp verses my sql
Php verses my sql
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO Objects
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For Beginners
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
PDO Basics - PHPMelb 2014
PDO Basics - PHPMelb 2014PDO Basics - PHPMelb 2014
PDO Basics - PHPMelb 2014
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
 
Cake PHP 3 Presentaion
Cake PHP 3 PresentaionCake PHP 3 Presentaion
Cake PHP 3 Presentaion
 
Php and database functionality
Php and database functionalityPhp and database functionality
Php and database functionality
 

Destaque

iMeeting: presentacion de Beatriz Casado
iMeeting: presentacion de Beatriz CasadoiMeeting: presentacion de Beatriz Casado
iMeeting: presentacion de Beatriz CasadoAgencia IDEA
 
Presentación Barómetro Andalucía 2012
Presentación Barómetro Andalucía 2012Presentación Barómetro Andalucía 2012
Presentación Barómetro Andalucía 2012Agencia IDEA
 
Exportaciones Andalucia 2012
Exportaciones Andalucia 2012Exportaciones Andalucia 2012
Exportaciones Andalucia 2012Agencia IDEA
 
iMeeting: conclusiones del Encuentro europeo de política regional
iMeeting: conclusiones del Encuentro europeo de política regionaliMeeting: conclusiones del Encuentro europeo de política regional
iMeeting: conclusiones del Encuentro europeo de política regionalAgencia IDEA
 
Els Resultats del Sistema de Finançament Pactat el 2009
Els Resultats del Sistema de Finançament Pactat el 2009Els Resultats del Sistema de Finançament Pactat el 2009
Els Resultats del Sistema de Finançament Pactat el 2009Miqui Mel
 
Experiencias de instrumentos públicos para la financiación empresarial
Experiencias de instrumentos públicos para la financiación empresarialExperiencias de instrumentos públicos para la financiación empresarial
Experiencias de instrumentos públicos para la financiación empresarialAgencia IDEA
 
Agencia IDEA: incentivos a la I+D+i
Agencia IDEA: incentivos a la I+D+iAgencia IDEA: incentivos a la I+D+i
Agencia IDEA: incentivos a la I+D+iAgencia IDEA
 
Msphdbrochure iit m
Msphdbrochure iit mMsphdbrochure iit m
Msphdbrochure iit mbikram ...
 

Destaque (8)

iMeeting: presentacion de Beatriz Casado
iMeeting: presentacion de Beatriz CasadoiMeeting: presentacion de Beatriz Casado
iMeeting: presentacion de Beatriz Casado
 
Presentación Barómetro Andalucía 2012
Presentación Barómetro Andalucía 2012Presentación Barómetro Andalucía 2012
Presentación Barómetro Andalucía 2012
 
Exportaciones Andalucia 2012
Exportaciones Andalucia 2012Exportaciones Andalucia 2012
Exportaciones Andalucia 2012
 
iMeeting: conclusiones del Encuentro europeo de política regional
iMeeting: conclusiones del Encuentro europeo de política regionaliMeeting: conclusiones del Encuentro europeo de política regional
iMeeting: conclusiones del Encuentro europeo de política regional
 
Els Resultats del Sistema de Finançament Pactat el 2009
Els Resultats del Sistema de Finançament Pactat el 2009Els Resultats del Sistema de Finançament Pactat el 2009
Els Resultats del Sistema de Finançament Pactat el 2009
 
Experiencias de instrumentos públicos para la financiación empresarial
Experiencias de instrumentos públicos para la financiación empresarialExperiencias de instrumentos públicos para la financiación empresarial
Experiencias de instrumentos públicos para la financiación empresarial
 
Agencia IDEA: incentivos a la I+D+i
Agencia IDEA: incentivos a la I+D+iAgencia IDEA: incentivos a la I+D+i
Agencia IDEA: incentivos a la I+D+i
 
Msphdbrochure iit m
Msphdbrochure iit mMsphdbrochure iit m
Msphdbrochure iit m
 

Semelhante a Using php with my sql

Collection of built in functions for manipulating MySQL databases.docx
Collection of built in functions for manipulating MySQL databases.docxCollection of built in functions for manipulating MySQL databases.docx
Collection of built in functions for manipulating MySQL databases.docxKingKhaliilHayat
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sqlsaritasingh19866
 
Web app development_crud_13
Web app development_crud_13Web app development_crud_13
Web app development_crud_13Hassen Poreya
 
Php and MySQL Web Development
Php and MySQL Web DevelopmentPhp and MySQL Web Development
Php and MySQL Web Developmentw3ondemand
 
9780538745840 ppt ch08
9780538745840 ppt ch089780538745840 ppt ch08
9780538745840 ppt ch08Terry Yoast
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDhivyaa C.R
 
Intro to PECL/mysqlnd_ms (4/7/2011)
Intro to PECL/mysqlnd_ms (4/7/2011)Intro to PECL/mysqlnd_ms (4/7/2011)
Intro to PECL/mysqlnd_ms (4/7/2011)Chris Barber
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbaiaadi Surve
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesRasan Samarasinghe
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPVineet Kumar Saini
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionRifat Nabi
 
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 7Mohd Harris Ahmad Jaal
 
Php mysql connectivity
Php mysql connectivityPhp mysql connectivity
Php mysql connectivityabhikwb
 
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxModule 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxmoirarandell
 
Php Data Objects
Php Data ObjectsPhp Data Objects
Php Data Objectshiren.joshi
 

Semelhante a Using php with my sql (20)

PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
 
Collection of built in functions for manipulating MySQL databases.docx
Collection of built in functions for manipulating MySQL databases.docxCollection of built in functions for manipulating MySQL databases.docx
Collection of built in functions for manipulating MySQL databases.docx
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sql
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Web app development_crud_13
Web app development_crud_13Web app development_crud_13
Web app development_crud_13
 
Php and MySQL Web Development
Php and MySQL Web DevelopmentPhp and MySQL Web Development
Php and MySQL Web Development
 
Php summary
Php summaryPhp summary
Php summary
 
9780538745840 ppt ch08
9780538745840 ppt ch089780538745840 ppt ch08
9780538745840 ppt ch08
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
 
Intro to PECL/mysqlnd_ms (4/7/2011)
Intro to PECL/mysqlnd_ms (4/7/2011)Intro to PECL/mysqlnd_ms (4/7/2011)
Intro to PECL/mysqlnd_ms (4/7/2011)
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
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
 
Php mysql connectivity
Php mysql connectivityPhp mysql connectivity
Php mysql connectivity
 
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxModule 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
 
Php Data Objects
Php Data ObjectsPhp Data Objects
Php Data Objects
 

Mais de salissal

Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debuggingsalissal
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessionssalissal
 
Web application security
Web application securityWeb application security
Web application securitysalissal
 
Developing web applications
Developing web applicationsDeveloping web applications
Developing web applicationssalissal
 
Programming with php
Programming with phpProgramming with php
Programming with phpsalissal
 
Dynamic website
Dynamic websiteDynamic website
Dynamic websitesalissal
 

Mais de salissal (8)

Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debugging
 
My sql
My sqlMy sql
My sql
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Web application security
Web application securityWeb application security
Web application security
 
Developing web applications
Developing web applicationsDeveloping web applications
Developing web applications
 
Programming with php
Programming with phpProgramming with php
Programming with php
 
Basic php
Basic phpBasic php
Basic php
 
Dynamic website
Dynamic websiteDynamic website
Dynamic website
 

Último

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Último (20)

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

Using php with my sql

  • 1. Connecting to MySQL and Selecting the Database Pengaturcaraan PHP Pengaturcaraan PHP The first step when dealing with the MySQL client and connecting to the server requires the appropriately named mysql_connect() function: 1
  • 2. Pengaturcaraan PHP Once you have connected to MySQL, you will need to select the database with which you want to work. This is the equivalent of saying USE databasename within the mysql client and is accomplished with the mysql_select_ db() function: Let's start the demonstration of connecting to MySQL by creating a special file just for that purpose. Other PHP scripts that require a MySQL connection can include this file. We'll also make use of the mysql_error() function. Pengaturcaraan PHP To connect to and select a database, first create a new PHP document in your text editor, mysql_connect.php. Connect PHP with mySQL <? $dbhost = "localhost"; $dbname = “pentadbiran"; $dbuser = “admin"; $dbpass = “123456"; mysql_connect("$dbhost","$dbuser","$dbpass"); @mysql_select_db($dbname) or die( "Unable to select database"); ?> 2
  • 3. Pengaturcaraan PHP Since this file contains information that must be kept private, we'll use a .php extension. By doing so, even if malicious users ran this script in their Web browser, they would not see the page's actual content. Be sure to save the file as mysql_connect.php. Upload the file to your server, outside of the Web document root. Because the file contains sensitive MySQL access information, it ought to be stored securely. If you can, place it in the directory immediately above, or otherwise outside, of the Web directory. This way the file will not be accessible from a Web browser. Pengaturcaraan PHP Temporarily place a copy of the script within the Web document root and run the script in your Web browser. In order to test the script, you'll want to place a copy on the server so that it's accessible from the Web browser (which means it must be in the Web directory). If the script works properly, the result should be a blank page. If you see an "Access denied..." or similar message, it means that the combination of username, password, and host does not have permission to access the particular database. 3
  • 4. Executing Simple Queries Pengaturcaraan PHP Pengaturcaraan PHP The following is a simple PHP function for executing a query: For simple queries like INSERT, UPDATE, DELETE, etc. (which do not return records), the $result variable will be either TRUE or FALSE depending upon whether the query executed successfully. For complex queries that do return records (SELECT, SHOW, DESCRIBE, CREATE, and EXPLAIN), the $result variable will be a resource link to the results of the query if it worked, or be FALSE if it did not. 4
  • 5. Pengaturcaraan PHP Retrieve data with mySQL+PHP Example : $query="SELECT * FROM member where nokp=‘123456'"; $result=mysql_query($query); while ($myrow = mysql_fetch_array($result)) { $id=$myrow["id"]; $login=$myrow["login"]; print “$id - $login<br>”; } Pengaturcaraan PHP Retrieve data with mySQL+PHP Contoh : $query="SELECT * FROM member where nokp=‘$nokp’"; $result=mysql_query($query); while ($myrow = mysql_fetch_rows($result)) { $id=$myrow[0]; $login=$myrow[1]; } print “$id - $login”; 5
  • 6. Pengaturcaraan PHP One final, albeit optional, step in your script would be to close the existing MySQL connection once you're finished with it: This function is not required, because PHP will automatically close the connection at the end of a script, but it does make for good programming form to incorporate it. Retrieving Query Results Pengaturcaraan PHP 6
  • 7. Pengaturcaraan PHP The primary tool for handling SELECT query results is mysql_fetch_array(), which takes the query result variable and returns one row of data at a time in an array format. You'll want to use this function within a loop that will continue to access every returned row as long as there are more to be read. The mysql_fetch_array() function takes an optional parameter specifying what type of array is returned: associative, indexed, or both. An associative array allows you to refer to column values by name, whereas an indexed array requires you to use only numbers (starting at 0 for the first column returned). Pengaturcaraan PHP Each parameter is defined by a constant. The MYSQL_NUM setting is marginally faster (and uses less memory) than the other options. Conversely, MYSQL_ASSOC is more specific ($row['column'] rather than $row[3]) and will continue to work even if the table structure or query changes. The table below lists the basic construction for reading every record from a query. Adding one of these constants as an optional parameter to the mysql_fetch_array() function dictates how you can access the values returned. The default setting of the function is MYSQL_BOTH. Constant Example MYSQL_ASSOC $row[0] or $row['column'] MYSQL_NUM $row[0] MYSQL_BOTH $row['column'] 7
  • 8. Pengaturcaraan PHP An optional step you can take when using mysql_fetch_array() would be to free up the query result resources once you are done using them: Counting Returned Records Pengaturcaraan PHP 8
  • 9. Pengaturcaraan PHP The logical function mysql_num_rows()returns the number of rows retrieved by a SELECT query, taking the query result as a parameter. Pengaturcaraan PHP Count data with mysql+PHP Example : $names = mysql_query("SELECT * FROM member WHERE login='$login'"); $num = mysql_num_rows($names); Or $total_results = mysql_result(mysql_query("SELECT COUNT(*) as Num FROM member where login=‘$login'"),0); $total_pages = ceil($total_results); 9
  • 10. Updating Records with PHP Pengaturcaraan PHP Pengaturcaraan PHP Update (single data) with mySQL+PHP Contoh : mysql_db_query($dbname, “update table set nama=“ahmad” where nokp=‘123456'"); Or mysql_db_query($dbname, “update table set nama=“$nama” where nokp=‘$nokp'"); 10
  • 11. Pengaturcaraan PHP Update (multiple data) with mySQL+PHP Example : mysql_db_query($dbname, “update table set nama=“ahmad”, jantina=“lelaki” where nokp=‘123456'"); Or mysql_db_query($dbname, “update table set nama=“$nama”, jantina=‘$jantina’ where nokp=‘$nokp'"); Inserting Records Pengaturcaraan PHP 11
  • 12. Pengaturcaraan PHP Insert data with mySQL+PHP Example mysql_db_query($dbname, "insert into $table values ('','$nama','$nokp','$jantina')"); Or mysql_db_query($dbname, "insert into members values ('','$nama','$nokp','$jantina')"); Deleting Records Pengaturcaraan PHP 12
  • 13. Pengaturcaraan PHP Delete Record with mySQL+PHP Example : mysql_db_query($dbname, "delete from $table where nama=‘ahmad'"); Or mysql_db_query($dbname, "delete from $table where nama=‘$nama'"); End Pengaturcaraan PHP 13