SlideShare a Scribd company logo
  PHP and MySQL  Prepared By: Md. Sirajus Salayhin Assistant Programmer Nanosoft Email:  [email_address] Web: http://nanoit.biz
PHP Language A recursive acronym:  P HP  H ypertext  P reprocessor A scripting language designed for creating dynamic and data-driven Web pages  PHP is a server-side scripting language; it is parsed and interpreted on the server side of a Web application and the resulting output is sent to the browser. (VBScript and JavaScript are mostly client-side). Designed to work with the MySQL database system, but can also connect to other database systems.
PHP Language PHP and MySQL are open-source; they can be obtained free-of-charge and the source codes are available for development. www.php.net www.mysql.com You will need to install PHP to work with your MS IIS or Apache Web server. PHP and MySQL are becoming increasingly popular in recent years because it is free of charge. Other software packages like Microsoft ASP.NET are expensive for small and medium enterprises.
A Simple PHP Example <HTML> <HEAD> <TITLE>PHP Example</TITLE> </HEAD> <BODY> <? echo &quot;<b>Welcome</b>&quot;; // print the string here ?> </BODY> </HTML> PHP scripts are enclosed by the  <?php  And  ?>  tags. Can simply use  <?  for the opening tag. All PHP statements end with a semicolon (unless it ends the closing tag on the same line) ‏ Comments can be marked by  # ,  //  or  /* */
Including Files You can include common files (like header, footer, and navigation bars) in PHP. <? include(&quot;header.inc&quot;) ?>
Variables in PHP Variable names start with the dollar sign $ You can use letters and underscore for variable names.  The first character after $ cannot be a number Variable names are case-sensitive For example: <? $name = &quot;Michael&quot;; ?> <? $i = 1; ?>
Variables in PHP The three main types of variables in PHP: Scalar Array Object Scalar can be Integer, Double, Boolean, or String When you assign a value to a variable, its data type is also assigned.
Array Arrays can be created with integers or strings as keys.  <?php $arr = array(&quot;UK&quot; => &quot;London&quot;, 12 => 56); echo $arr[&quot;UK&quot;]; // London echo $arr[12];    // 56 ?>
Object Use the  class  statement to define a class. Use the  new  statement to create an object. <?php class test {    function do_something()    {        echo &quot;Do something&quot;;     } } $my_test = new test; $my_test->do_something(); ?>
Basic Operators Assignment/Arithmetic operators = + - * / % ++ -- += -= *= /= Comparison operators ==  (equal value) ‏ ===  (identical value and data type) ‏ !=  or  <> < > <= >= Logical operators ! && ||
String Concatenation Same as Perl . concatenate strings .=  concatenate and assign Example: $word1 = &quot;Play&quot;;  $full_string = $word1 . &quot;Station&quot;;
String Functions There are a lot of string functions in PHP that you can use. For example: int strlen(string str) ‏ string strtoupper(string str) ‏ string strtolower(string str) ‏ int strcmp(string str1, string str2) ‏ int strcasecmp(string str1, string str2) ‏ string strstr(string src, string target) ‏ int strpos(string src, string target [, int offset]) ‏ You can find them in the PHP manual: http://www.php.net/manual/en/
Conditions boolean variable: TRUE(1) or FALSE(0) ‏ if (EXPR) { STATEMENTS; }  elseif (EXPR) { STATEMENTS; } else { STATEMENTS; } switch-case
Loops while ( EXPR )  { STATEMENTS; }  do { STATEMENTS;  } while (EXPR); for ( INIT_EXPR; COND_EXPR; LOOP_EXPR )  { STATEMENTS; }   foreach (ARRAY as VARIABLE)  { STATEMENTS; } break, continue
Alternative Syntax It is possible to write control statements and loops using the following “colon” format: <?php  if ($a == 5):   echo &quot;A is equal to 5&quot;;  endif; ?>
User-defined Functions Functions can be defined using the  function  keyword. <?php function function_name($arg_1, $arg_2, ...) {    statements;    return $some_value; // optional  } ?>
Mixing HTML and PHP Codes PHP codes can be easily inserted anywhere in an HTML page.  You can even mix the codes together, usually to avoid writing too many “echo” statements with escape characters. <?  if ($i == 1) {  ?>   <h2>The condition is true</h2>   <center><b>$i is 1</b></center> <?  } else {  ?>   <h2>The condition is false</h2>   <center><b>$i is not 1</b></center> <?  }  ?>  HTML PHP
Shortcut for Writing Echos Instead of writing  <? echo expression ?> You can use the following shortcut <?= expression ?> This is useful for inserting expressions and variables quickly into HTML pages.
Working with HTML Forms You can easily get the variables submitted by an HTML form using the following (assume the form input is called “name”: $_POST['name'] // post method $_GET['name'] // get method $name /* easier, but Register Globals must be set to ON in PHP config */
Working with HTML Forms It is common to put the form and the results of different requests in the same file. <HTML> <HEAD><TITLE>PHP FORM TEST</TITLE></HEAD> <BODY> <? if (!isset($name) || $name == &quot;&quot;) { ?> <FORM METHOD=&quot;post&quot;> Your name: <INPUT TYPE=&quot;text&quot; NAME=&quot;name&quot;> Your age: <INPUT TYPE=&quot;text&quot; NAME=&quot;age&quot;> <INPUT TYPE=&quot;submit&quot;> </FORM> <? } else { echo &quot;Your name is $name<BR>&quot;; echo &quot;Your age is $age&quot;; } ?> </BODY> </HTML> If name is empty or not defined, then show the form If name is not empty, i.e., when the user has entered something, then show the results
PHP and MySQL PHP is designed to work with the MySQL database. However, it can also connect to other database systems such as Oracle, Sybase, etc., using ODBC.
Example <HTML> <BODY>  <?php  $db = mysql_connect(&quot;localhost&quot;, &quot;root“,””);  mysql_select_db(&quot;mydb &quot; , $db);  $result = mysql_query(&quot;SELECT * FROM employees&quot;,$db);  printf(&quot;First Name: %s<br>\n&quot;, mysql_result($result,0,&quot;first&quot;));  printf(&quot;Last Name: %s<br>\n&quot;, mysql_result($result,0,&quot;last&quot;));  printf(&quot;Address: %s<br>\n&quot;, mysql_result($result,0,&quot;address&quot;));  printf(&quot;Position: %s<br>\n&quot;,mysql_result($result,0,&quot;position&quot;));  mysql_free_result($result); mysql_close($db); ?>  </BODY> </HTML>
Useful PHP Functions for MySQL mysql_connect(host, username [,password]); Connects to a MySQL server on the specified host using the given username and/or password. Returns a MySQL link identifier on success, or FALSE on failure.  mysql_select_db(db_name [,resource]) ‏ Selects a database from the database server.
Useful PHP Functions for MySQL mysql_query(SQL, resource);  Sends the specified SQL query to the database specified by the resource identifier. The retrieved data are returned by the function as a MySQL result set.  mysql_result(result, row [,field]);  Returns the contents of one cell from a MySQL result set. The field argument can be the field name or the field’s offset. mysql_fetch_array(result [,result_type]) ‏ Fetch a result row as an associative array, a numeric array, or both. The result type can take the constants MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.
Useful PHP Functions for MySQL mysql_free_result(result) ‏ Frees the result set mysql_close(resource) ‏ Closes the connection to the database.
Error Handling If there is error in the database connection, you can terminate the current script  by using the  die  function. For example: $db = mysql_connect(&quot;localhost&quot;, &quot;root“, “”)  or die(&quot;Could not connect : &quot; . mysql_error()); mysql_select_db(&quot;my_database&quot;)  or die(&quot;Could not select database&quot;); $result = mysql_query($query)  or die(&quot;Query failed&quot;);
Example: Looping through the Cells <?php /* Connecting, selecting database */ $link = mysql_connect(&quot;mysql_host&quot;, &quot;mysql_user&quot;, mysql_password&quot;) ‏ or die(&quot;Could not connect : &quot; . mysql_error()); echo &quot;Connected successfully&quot;; mysql_select_db(&quot;my_database&quot;) or die(&quot;Could not select database&quot;); /* Performing SQL query */ $query = &quot;SELECT * FROM my_table&quot;; $result = mysql_query($query)  or die(&quot;Query failed : &quot; . mysql_error()); /* Printing results in HTML */ echo &quot;<table>\n&quot;; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { echo &quot;\t<tr>\n&quot;; foreach ($line as $col_value) { echo &quot;\t\t<td>$col_value</td>\n&quot;; } echo &quot;\t</tr>\n&quot;; } echo &quot;</table>\n&quot;; Loop through each row of the result set Loop through each element in a row
Example: Looping through the Cells /* Free resultset */ mysql_free_result($result); /* Closing connection */ mysql_close($link); ?>
Thank You Question ??
Ad

More Related Content

What's hot (19)

Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
Tiji Thomas
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
Muthuselvam RS
 
phptutorial
phptutorialphptutorial
phptutorial
tutorialsruby
 
Web development
Web developmentWeb development
Web development
Seerat Bakhtawar
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
KIRAN KUMAR SILIVERI
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
Muhamad Al Imran
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomer
Shivi Tomer
 
Session Server - Maintaing State between several Servers
Session Server - Maintaing State between several ServersSession Server - Maintaing State between several Servers
Session Server - Maintaing State between several Servers
Stephan Schmidt
 
Chapter 02 php basic syntax
Chapter 02   php basic syntaxChapter 02   php basic syntax
Chapter 02 php basic syntax
Dhani Ahmad
 
Inroduction to XSLT with PHP4
Inroduction to XSLT with PHP4Inroduction to XSLT with PHP4
Inroduction to XSLT with PHP4
Stephan Schmidt
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
Gheyath M. Othman
 
Php mysql
Php mysqlPhp mysql
Php mysql
Shehrevar Davierwala
 
The Big Documentation Extravaganza
The Big Documentation ExtravaganzaThe Big Documentation Extravaganza
The Big Documentation Extravaganza
Stephan Schmidt
 
XML and PHP 5
XML and PHP 5XML and PHP 5
XML and PHP 5
Adam Trachtenberg
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
Dr. Ramkumar Lakshminarayanan
 
Php basics
Php basicsPhp basics
Php basics
Jamshid Hashimi
 
PEAR For The Masses
PEAR For The MassesPEAR For The Masses
PEAR For The Masses
Stephan Schmidt
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
Jussi Pohjolainen
 
Php
PhpPhp
Php
Shyam Khant
 

Viewers also liked (20)

01 las sociedades_en_el_peru
01 las sociedades_en_el_peru01 las sociedades_en_el_peru
01 las sociedades_en_el_peru
Mariela Paredes Rojas
 
Que es la energía 2
Que es la energía 2Que es la energía 2
Que es la energía 2
mayi12
 
Luokk6, 3. kerta syksy 2011
Luokk6, 3. kerta syksy 2011Luokk6, 3. kerta syksy 2011
Luokk6, 3. kerta syksy 2011
Mikko Horila
 
Vrealize automotion
Vrealize automotionVrealize automotion
Vrealize automotion
Andrey Tokarchuk
 
LinkedIn Workshop for International PhD researchers at Utrecht University
LinkedIn Workshop for International PhD researchers at Utrecht UniversityLinkedIn Workshop for International PhD researchers at Utrecht University
LinkedIn Workshop for International PhD researchers at Utrecht University
Petra Fisher
 
Job search boot camp
Job search boot campJob search boot camp
Job search boot camp
nolken
 
Las clases de energía
Las clases de energíaLas clases de energía
Las clases de energía
mayi12
 
La energía y sus fuentes
La energía y sus fuentes La energía y sus fuentes
La energía y sus fuentes
mayi12
 
Brazil 16 people dead
Brazil  16 people deadBrazil  16 people dead
Brazil 16 people dead
nickolas5696
 
Luokk6 2. kerta
Luokk6 2. kertaLuokk6 2. kerta
Luokk6 2. kerta
Mikko Horila
 
CYA - Cover Your Assets. Disaster Recovery 101
CYA - Cover Your Assets. Disaster Recovery 101CYA - Cover Your Assets. Disaster Recovery 101
CYA - Cover Your Assets. Disaster Recovery 101
Auskosh
 
Epistemologia computacional: intrudução
Epistemologia computacional: intruduçãoEpistemologia computacional: intrudução
Epistemologia computacional: intrudução
Danilo Fraga Dantas
 
La belleza de los árboles
La belleza de los árbolesLa belleza de los árboles
La belleza de los árboles
elcuetodelmoro
 
Dudas cientificas
Dudas cientificasDudas cientificas
Dudas cientificas
elcuetodelmoro
 
Spiceworks Unplugged Boston, July 19, 2012
Spiceworks Unplugged Boston, July 19, 2012Spiceworks Unplugged Boston, July 19, 2012
Spiceworks Unplugged Boston, July 19, 2012
Auskosh
 
Ten Things You May Have Not Known About Your Chamber
Ten Things You May Have Not Known About Your ChamberTen Things You May Have Not Known About Your Chamber
Ten Things You May Have Not Known About Your Chamber
Kristen Smith
 
Webinar: State Innovation Models Initiative for State Officials - Model Design
Webinar: State Innovation Models Initiative for State Officials - Model DesignWebinar: State Innovation Models Initiative for State Officials - Model Design
Webinar: State Innovation Models Initiative for State Officials - Model Design
Centers for Medicare & Medicaid Services (CMS)
 
CSS
CSSCSS
CSS
Md. Sirajus Salayhin
 
Legalni i piratski softver
Legalni i piratski softverLegalni i piratski softver
Legalni i piratski softver
Osnovna škola "Žarko Zrenjanin"
 
Nonlinear power point
Nonlinear power pointNonlinear power point
Nonlinear power point
Schmity50
 
Que es la energía 2
Que es la energía 2Que es la energía 2
Que es la energía 2
mayi12
 
Luokk6, 3. kerta syksy 2011
Luokk6, 3. kerta syksy 2011Luokk6, 3. kerta syksy 2011
Luokk6, 3. kerta syksy 2011
Mikko Horila
 
LinkedIn Workshop for International PhD researchers at Utrecht University
LinkedIn Workshop for International PhD researchers at Utrecht UniversityLinkedIn Workshop for International PhD researchers at Utrecht University
LinkedIn Workshop for International PhD researchers at Utrecht University
Petra Fisher
 
Job search boot camp
Job search boot campJob search boot camp
Job search boot camp
nolken
 
Las clases de energía
Las clases de energíaLas clases de energía
Las clases de energía
mayi12
 
La energía y sus fuentes
La energía y sus fuentes La energía y sus fuentes
La energía y sus fuentes
mayi12
 
Brazil 16 people dead
Brazil  16 people deadBrazil  16 people dead
Brazil 16 people dead
nickolas5696
 
CYA - Cover Your Assets. Disaster Recovery 101
CYA - Cover Your Assets. Disaster Recovery 101CYA - Cover Your Assets. Disaster Recovery 101
CYA - Cover Your Assets. Disaster Recovery 101
Auskosh
 
Epistemologia computacional: intrudução
Epistemologia computacional: intruduçãoEpistemologia computacional: intrudução
Epistemologia computacional: intrudução
Danilo Fraga Dantas
 
La belleza de los árboles
La belleza de los árbolesLa belleza de los árboles
La belleza de los árboles
elcuetodelmoro
 
Spiceworks Unplugged Boston, July 19, 2012
Spiceworks Unplugged Boston, July 19, 2012Spiceworks Unplugged Boston, July 19, 2012
Spiceworks Unplugged Boston, July 19, 2012
Auskosh
 
Ten Things You May Have Not Known About Your Chamber
Ten Things You May Have Not Known About Your ChamberTen Things You May Have Not Known About Your Chamber
Ten Things You May Have Not Known About Your Chamber
Kristen Smith
 
Nonlinear power point
Nonlinear power pointNonlinear power point
Nonlinear power point
Schmity50
 
Ad

Similar to PHP MySQL (20)

Introduction To Lamp
Introduction To LampIntroduction To Lamp
Introduction To Lamp
Amzad Hossain
 
Dynamic Web Pages Ch 1 V1.0
Dynamic Web Pages Ch 1 V1.0Dynamic Web Pages Ch 1 V1.0
Dynamic Web Pages Ch 1 V1.0
Cathie101
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
webhostingguy
 
P H P Part I I, By Kian
P H P  Part  I I,  By  KianP H P  Part  I I,  By  Kian
P H P Part I I, By Kian
phelios
 
Babitha5.php
Babitha5.phpBabitha5.php
Babitha5.php
banubabitha
 
Babitha5.php
Babitha5.phpBabitha5.php
Babitha5.php
banubabitha
 
Php
PhpPhp
Php
WAHEEDA ROOHILLAH
 
Babitha5.php
Babitha5.phpBabitha5.php
Babitha5.php
banubabitha
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
mussawir20
 
John Rowley Notes
John Rowley NotesJohn Rowley Notes
John Rowley Notes
IBAT College
 
What Is Php
What Is PhpWhat Is Php
What Is Php
AVC
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
Php intro
Php introPhp intro
Php intro
Rajesh Jha
 
Php1
Php1Php1
Php1
Keennary Pungyera
 
course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpoint
webhostingguy
 
Justmeans power point
Justmeans power pointJustmeans power point
Justmeans power point
justmeanscsr
 
Justmeans power point
Justmeans power pointJustmeans power point
Justmeans power point
justmeanscsr
 
Justmeans power point
Justmeans power pointJustmeans power point
Justmeans power point
justmeanscsr
 
Justmeans power point
Justmeans power pointJustmeans power point
Justmeans power point
justmeanscsr
 
Introduction To Lamp
Introduction To LampIntroduction To Lamp
Introduction To Lamp
Amzad Hossain
 
Dynamic Web Pages Ch 1 V1.0
Dynamic Web Pages Ch 1 V1.0Dynamic Web Pages Ch 1 V1.0
Dynamic Web Pages Ch 1 V1.0
Cathie101
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
webhostingguy
 
P H P Part I I, By Kian
P H P  Part  I I,  By  KianP H P  Part  I I,  By  Kian
P H P Part I I, By Kian
phelios
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
mussawir20
 
What Is Php
What Is PhpWhat Is Php
What Is Php
AVC
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpoint
webhostingguy
 
Justmeans power point
Justmeans power pointJustmeans power point
Justmeans power point
justmeanscsr
 
Justmeans power point
Justmeans power pointJustmeans power point
Justmeans power point
justmeanscsr
 
Justmeans power point
Justmeans power pointJustmeans power point
Justmeans power point
justmeanscsr
 
Justmeans power point
Justmeans power pointJustmeans power point
Justmeans power point
justmeanscsr
 
Ad

Recently uploaded (20)

How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
MINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PRMINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PR
MIND CTI
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
Financial Services Technology Summit 2025
Financial Services Technology Summit 2025Financial Services Technology Summit 2025
Financial Services Technology Summit 2025
Ray Bugg
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Vaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without HallucinationsVaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without Hallucinations
john409870
 
The Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI IntegrationThe Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI Integration
Re-solution Data Ltd
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and MLGyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
Gyrus AI
 
Play It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google CertificatePlay It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
MINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PRMINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PR
MIND CTI
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
Financial Services Technology Summit 2025
Financial Services Technology Summit 2025Financial Services Technology Summit 2025
Financial Services Technology Summit 2025
Ray Bugg
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Vaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without HallucinationsVaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without Hallucinations
john409870
 
The Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI IntegrationThe Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI Integration
Re-solution Data Ltd
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and MLGyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
Gyrus AI
 
Play It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google CertificatePlay It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 

PHP MySQL

  • 1. PHP and MySQL Prepared By: Md. Sirajus Salayhin Assistant Programmer Nanosoft Email: [email_address] Web: http://nanoit.biz
  • 2. PHP Language A recursive acronym: P HP H ypertext P reprocessor A scripting language designed for creating dynamic and data-driven Web pages PHP is a server-side scripting language; it is parsed and interpreted on the server side of a Web application and the resulting output is sent to the browser. (VBScript and JavaScript are mostly client-side). Designed to work with the MySQL database system, but can also connect to other database systems.
  • 3. PHP Language PHP and MySQL are open-source; they can be obtained free-of-charge and the source codes are available for development. www.php.net www.mysql.com You will need to install PHP to work with your MS IIS or Apache Web server. PHP and MySQL are becoming increasingly popular in recent years because it is free of charge. Other software packages like Microsoft ASP.NET are expensive for small and medium enterprises.
  • 4. A Simple PHP Example <HTML> <HEAD> <TITLE>PHP Example</TITLE> </HEAD> <BODY> <? echo &quot;<b>Welcome</b>&quot;; // print the string here ?> </BODY> </HTML> PHP scripts are enclosed by the <?php And ?> tags. Can simply use <? for the opening tag. All PHP statements end with a semicolon (unless it ends the closing tag on the same line) ‏ Comments can be marked by # , // or /* */
  • 5. Including Files You can include common files (like header, footer, and navigation bars) in PHP. <? include(&quot;header.inc&quot;) ?>
  • 6. Variables in PHP Variable names start with the dollar sign $ You can use letters and underscore for variable names. The first character after $ cannot be a number Variable names are case-sensitive For example: <? $name = &quot;Michael&quot;; ?> <? $i = 1; ?>
  • 7. Variables in PHP The three main types of variables in PHP: Scalar Array Object Scalar can be Integer, Double, Boolean, or String When you assign a value to a variable, its data type is also assigned.
  • 8. Array Arrays can be created with integers or strings as keys. <?php $arr = array(&quot;UK&quot; => &quot;London&quot;, 12 => 56); echo $arr[&quot;UK&quot;]; // London echo $arr[12];    // 56 ?>
  • 9. Object Use the class statement to define a class. Use the new statement to create an object. <?php class test {    function do_something()    {        echo &quot;Do something&quot;;    } } $my_test = new test; $my_test->do_something(); ?>
  • 10. Basic Operators Assignment/Arithmetic operators = + - * / % ++ -- += -= *= /= Comparison operators == (equal value) ‏ === (identical value and data type) ‏ != or <> < > <= >= Logical operators ! && ||
  • 11. String Concatenation Same as Perl . concatenate strings .= concatenate and assign Example: $word1 = &quot;Play&quot;; $full_string = $word1 . &quot;Station&quot;;
  • 12. String Functions There are a lot of string functions in PHP that you can use. For example: int strlen(string str) ‏ string strtoupper(string str) ‏ string strtolower(string str) ‏ int strcmp(string str1, string str2) ‏ int strcasecmp(string str1, string str2) ‏ string strstr(string src, string target) ‏ int strpos(string src, string target [, int offset]) ‏ You can find them in the PHP manual: http://www.php.net/manual/en/
  • 13. Conditions boolean variable: TRUE(1) or FALSE(0) ‏ if (EXPR) { STATEMENTS; } elseif (EXPR) { STATEMENTS; } else { STATEMENTS; } switch-case
  • 14. Loops while ( EXPR ) { STATEMENTS; } do { STATEMENTS; } while (EXPR); for ( INIT_EXPR; COND_EXPR; LOOP_EXPR ) { STATEMENTS; } foreach (ARRAY as VARIABLE) { STATEMENTS; } break, continue
  • 15. Alternative Syntax It is possible to write control statements and loops using the following “colon” format: <?php if ($a == 5): echo &quot;A is equal to 5&quot;; endif; ?>
  • 16. User-defined Functions Functions can be defined using the function keyword. <?php function function_name($arg_1, $arg_2, ...) {    statements;    return $some_value; // optional } ?>
  • 17. Mixing HTML and PHP Codes PHP codes can be easily inserted anywhere in an HTML page. You can even mix the codes together, usually to avoid writing too many “echo” statements with escape characters. <? if ($i == 1) { ?> <h2>The condition is true</h2> <center><b>$i is 1</b></center> <? } else { ?> <h2>The condition is false</h2> <center><b>$i is not 1</b></center> <? } ?> HTML PHP
  • 18. Shortcut for Writing Echos Instead of writing <? echo expression ?> You can use the following shortcut <?= expression ?> This is useful for inserting expressions and variables quickly into HTML pages.
  • 19. Working with HTML Forms You can easily get the variables submitted by an HTML form using the following (assume the form input is called “name”: $_POST['name'] // post method $_GET['name'] // get method $name /* easier, but Register Globals must be set to ON in PHP config */
  • 20. Working with HTML Forms It is common to put the form and the results of different requests in the same file. <HTML> <HEAD><TITLE>PHP FORM TEST</TITLE></HEAD> <BODY> <? if (!isset($name) || $name == &quot;&quot;) { ?> <FORM METHOD=&quot;post&quot;> Your name: <INPUT TYPE=&quot;text&quot; NAME=&quot;name&quot;> Your age: <INPUT TYPE=&quot;text&quot; NAME=&quot;age&quot;> <INPUT TYPE=&quot;submit&quot;> </FORM> <? } else { echo &quot;Your name is $name<BR>&quot;; echo &quot;Your age is $age&quot;; } ?> </BODY> </HTML> If name is empty or not defined, then show the form If name is not empty, i.e., when the user has entered something, then show the results
  • 21. PHP and MySQL PHP is designed to work with the MySQL database. However, it can also connect to other database systems such as Oracle, Sybase, etc., using ODBC.
  • 22. Example <HTML> <BODY> <?php $db = mysql_connect(&quot;localhost&quot;, &quot;root“,””); mysql_select_db(&quot;mydb &quot; , $db); $result = mysql_query(&quot;SELECT * FROM employees&quot;,$db); printf(&quot;First Name: %s<br>\n&quot;, mysql_result($result,0,&quot;first&quot;)); printf(&quot;Last Name: %s<br>\n&quot;, mysql_result($result,0,&quot;last&quot;)); printf(&quot;Address: %s<br>\n&quot;, mysql_result($result,0,&quot;address&quot;)); printf(&quot;Position: %s<br>\n&quot;,mysql_result($result,0,&quot;position&quot;)); mysql_free_result($result); mysql_close($db); ?> </BODY> </HTML>
  • 23. Useful PHP Functions for MySQL mysql_connect(host, username [,password]); Connects to a MySQL server on the specified host using the given username and/or password. Returns a MySQL link identifier on success, or FALSE on failure. mysql_select_db(db_name [,resource]) ‏ Selects a database from the database server.
  • 24. Useful PHP Functions for MySQL mysql_query(SQL, resource); Sends the specified SQL query to the database specified by the resource identifier. The retrieved data are returned by the function as a MySQL result set. mysql_result(result, row [,field]); Returns the contents of one cell from a MySQL result set. The field argument can be the field name or the field’s offset. mysql_fetch_array(result [,result_type]) ‏ Fetch a result row as an associative array, a numeric array, or both. The result type can take the constants MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.
  • 25. Useful PHP Functions for MySQL mysql_free_result(result) ‏ Frees the result set mysql_close(resource) ‏ Closes the connection to the database.
  • 26. Error Handling If there is error in the database connection, you can terminate the current script by using the die function. For example: $db = mysql_connect(&quot;localhost&quot;, &quot;root“, “”) or die(&quot;Could not connect : &quot; . mysql_error()); mysql_select_db(&quot;my_database&quot;) or die(&quot;Could not select database&quot;); $result = mysql_query($query) or die(&quot;Query failed&quot;);
  • 27. Example: Looping through the Cells <?php /* Connecting, selecting database */ $link = mysql_connect(&quot;mysql_host&quot;, &quot;mysql_user&quot;, mysql_password&quot;) ‏ or die(&quot;Could not connect : &quot; . mysql_error()); echo &quot;Connected successfully&quot;; mysql_select_db(&quot;my_database&quot;) or die(&quot;Could not select database&quot;); /* Performing SQL query */ $query = &quot;SELECT * FROM my_table&quot;; $result = mysql_query($query) or die(&quot;Query failed : &quot; . mysql_error()); /* Printing results in HTML */ echo &quot;<table>\n&quot;; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { echo &quot;\t<tr>\n&quot;; foreach ($line as $col_value) { echo &quot;\t\t<td>$col_value</td>\n&quot;; } echo &quot;\t</tr>\n&quot;; } echo &quot;</table>\n&quot;; Loop through each row of the result set Loop through each element in a row
  • 28. Example: Looping through the Cells /* Free resultset */ mysql_free_result($result); /* Closing connection */ mysql_close($link); ?>