SlideShare a Scribd company logo
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

More Related Content

What's hot (17)

PPT
Php Mysql
Mudasir Syed
 
PDF
Mysql & Php
Inbal Geffen
 
ODP
Database Connection With Mysql
Harit Kothari
 
PPTX
Php mysq
prasanna pabba
 
PDF
lab56_db
tutorialsruby
 
PDF
Php verses MySQL
CBitss Technologies
 
PPTX
Learn PHP Lacture2
ADARSH BHATT
 
PDF
Future of HTTP in CakePHP
markstory
 
PDF
Advanced Querying with CakePHP 3
José Lorenzo Rodríguez Urdaneta
 
PPTX
Php verses my sql
SEO Training in Chandigarh
 
PPT
PHP - PDO Objects
AJINKYA N
 
PPT
Php MySql For Beginners
Priti Solanki
 
PPT
Quebec pdo
Valentine Dianov
 
PDF
PDO Basics - PHPMelb 2014
andrewdotcom
 
PDF
New in cakephp3
markstory
 
PPTX
Cake PHP 3 Presentaion
glslarmenta
 
PPTX
Php and database functionality
Sayed Ahmed
 
Php Mysql
Mudasir Syed
 
Mysql & Php
Inbal Geffen
 
Database Connection With Mysql
Harit Kothari
 
Php mysq
prasanna pabba
 
lab56_db
tutorialsruby
 
Php verses MySQL
CBitss Technologies
 
Learn PHP Lacture2
ADARSH BHATT
 
Future of HTTP in CakePHP
markstory
 
Advanced Querying with CakePHP 3
José Lorenzo Rodríguez Urdaneta
 
Php verses my sql
SEO Training in Chandigarh
 
PHP - PDO Objects
AJINKYA N
 
Php MySql For Beginners
Priti Solanki
 
Quebec pdo
Valentine Dianov
 
PDO Basics - PHPMelb 2014
andrewdotcom
 
New in cakephp3
markstory
 
Cake PHP 3 Presentaion
glslarmenta
 
Php and database functionality
Sayed Ahmed
 

Viewers also liked (8)

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

Similar to Using php with my sql (20)

PDF
PHP with MySQL
wahidullah mudaser
 
PDF
Php verses MySQL
CBitss Technologies
 
DOCX
Collection of built in functions for manipulating MySQL databases.docx
KingKhaliilHayat
 
PPT
Synapse india reviews on php and sql
saritasingh19866
 
PPT
Php with MYSQL Database
Computer Hardware & Trouble shooting
 
PDF
Web app development_crud_13
Hassen Poreya
 
PPT
Php and MySQL Web Development
w3ondemand
 
PPTX
chapter_Seven Database manipulation using php.pptx
Getawu
 
PPT
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
SenzotaSemakuwa
 
PDF
Php summary
Michelle Darling
 
PPTX
lecture 7 - Introduction to MySQL with PHP.pptx
AOmaAli
 
PPT
9780538745840 ppt ch08
Terry Yoast
 
PPTX
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
PPTX
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
KEY
Intro to PECL/mysqlnd_ms (4/7/2011)
Chris Barber
 
PPT
Php classes in mumbai
aadi Surve
 
PPSX
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
PDF
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Vineet Kumar Saini
 
PDF
Dependency Injection
Rifat Nabi
 
PPTX
Web Application Development using PHP Chapter 7
Mohd Harris Ahmad Jaal
 
PHP with MySQL
wahidullah mudaser
 
Php verses MySQL
CBitss Technologies
 
Collection of built in functions for manipulating MySQL databases.docx
KingKhaliilHayat
 
Synapse india reviews on php and sql
saritasingh19866
 
Php with MYSQL Database
Computer Hardware & Trouble shooting
 
Web app development_crud_13
Hassen Poreya
 
Php and MySQL Web Development
w3ondemand
 
chapter_Seven Database manipulation using php.pptx
Getawu
 
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
SenzotaSemakuwa
 
Php summary
Michelle Darling
 
lecture 7 - Introduction to MySQL with PHP.pptx
AOmaAli
 
9780538745840 ppt ch08
Terry Yoast
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
Intro to PECL/mysqlnd_ms (4/7/2011)
Chris Barber
 
Php classes in mumbai
aadi Surve
 
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Vineet Kumar Saini
 
Dependency Injection
Rifat Nabi
 
Web Application Development using PHP Chapter 7
Mohd Harris Ahmad Jaal
 
Ad

More from salissal (8)

PDF
Error handling and debugging
salissal
 
PDF
My sql
salissal
 
PDF
Cookies and sessions
salissal
 
PDF
Web application security
salissal
 
PDF
Developing web applications
salissal
 
PDF
Programming with php
salissal
 
PDF
Basic php
salissal
 
PDF
Dynamic website
salissal
 
Error handling and debugging
salissal
 
My sql
salissal
 
Cookies and sessions
salissal
 
Web application security
salissal
 
Developing web applications
salissal
 
Programming with php
salissal
 
Basic php
salissal
 
Dynamic website
salissal
 

Recently uploaded (20)

PPTX
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPTX
PPT on the Development of Education in the Victorian England
Beena E S
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PDF
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
PPTX
THE TAME BIRD AND THE FREE BIRD.pptxxxxx
MarcChristianNicolas
 
PPTX
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PPTX
Mathematics 5 - Time Measurement: Time Zone
menchreo
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPT on the Development of Education in the Victorian England
Beena E S
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
THE TAME BIRD AND THE FREE BIRD.pptxxxxx
MarcChristianNicolas
 
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
Mathematics 5 - Time Measurement: Time Zone
menchreo
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 

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