SlideShare a Scribd company logo
PHP and MySQL
PHP
• Creates DYNAMIC web pages
– HTML traditionally static
– Contents regenerated every time visit or reload site
• (e.g. can include current time)
• PHP is a scripting language
– Interpreted, not converted to binary executable files
– (Dialogue for play interpreted by actors)
– Strong at communicating with program components written in
other languages
• E.g. can embed PHP statements within HTML
PHP
• Written as a set of CGI binaries in C in 1994 by
R. Lerdorf
– Created to display resume and collect data about
page traffic, e.g. dynamic web pages
– Personal Home Page tools publicly released 1995
– In 1998 became PHP: Hypertext Preprocessor
• PHP parser with web server and web browser,
model similar to MS ASP.NET, Sun JavaServer
Pages
PHP
• Used mainly in server-side scripting
– Can be used from command line interface
– Standalone graphical applications
• Takes input from a file or stream containing text and PHP
instructions
• Outputs stream of data for display
• PHP 4 – parser compiles input to produce bytecode – Zend engine
(better performance than interpreted PHP 3)
• PHP 5 – robust support for OO programming, better support for
MySQL, support for SQLite, performance enhancements
PHP - specifics
• Delimiters: <?php ?> or just <? ?>
• PHP parses code within delimiters
• Code outside delimiter sent to output, not parsed
• Block comments /* */
• Inline comments // #
PHP vs. C++
• Similarities:
– Compiled Language
– Syntax nearly the same (For/While/If)
– Requires semicolons after each statement ;
– Assignment is right to left ($num = 56;)
– Object-Oriented (Class support, inheritance, virtuals,
polymorphism)
– Functions!
– Types are nearly the same (booleans, integers,
strings, etc.)
PHP Versus C++
• Differences:
– Variables begin with $ sign ($name = “John Doe”;)
– No explicit declaration of variable types
– Introduction of “lazy” functions (foreach, explode,
mail)
– No Function Overloading
– “Hidden” functions-within-a-function
– Compiled/interpreted during every page load
– Documented!
– Echo for output
PHP Versus C++
• Web Specific:
– Cookies and “Sessions”
– Dynamic HTML based on user-defined logic
– Interact and process a form’s action
– Process URL Parameters
– Easy Database Integration
– Cross-Site-Scripting (XSS) security hacks -
taken care of by PHP 5
• Allows code injection by web users into web pages
viewed by other users (e.g. phishing attacks)
Introducing/Review HTML
• Hyper Text Markup Language:
– Paired by angled brackets like XML (Ex. <font> </font>)
– Can use a “WYSIWYG” (what you see is what you get) program such as
FrontPage or Dreamweaver for development
– Dynamic web languages such as PHP simply produces HTML
MySQL
• MySQL queries same as SQL in Oracle
• Except it’s freeware!
• Has many of the same capabilities as
traditional DBMSs
– Multi-user, triggers, cursors, etc.
– Doesn’t get performance advantages
MySQL commands
mysql> CREATE TABLE table_name …
INSERT Into table_name …
mysql> LOAD DATA LOCAL INFILE “file_name” INTO
TABLE table_name;
mysql> file_name (containing a query)
mysql> SELECT … FROM … WHERE …
mysql> UPDATE …
mysql> DELETE …
MySQL commands
mysql> SHOW databases;
mysql> USE db_name;
mysql> SHOW tables;
mysql> DESCRIBE table_name;
mysql> create table …
mysql> insert into table values (…
mysql> select * from table_name;
Some php mysql functions
• Mysql_connect (“localhost”, “login”, “password”)
• Mysql_select_db (‘db_name’, $link_id)
• mysql_query (string [, resource $link_id])
– Executes a query, place result in variable, like a cursor
• mysql_error ( )
– Returns error message from previous sql operation
• mysql_fetch_array ($result, how)
– Traverses through cursor of query result
– How is either mysql_assoc (use col. names)
– Or mysql_num (use index number) or mysql_both
• Mysql_num_fields
PHP In Action
<?
echo "Welcome to Vrbsky's DB";
// Connect to MySQL
$link = mysql_connect("localhost", "svrbsky", “password");
if (!$link) {die('Not connected: '. mysql_error()); } // see if connected
// Select DB will use
$dbselected = mysql_select_db('cs457db', $link); // you may not have to do this
mysql_select_db('cs457db') or die ('Could not select database'); // see if worked
// Now the query
$query = "Select * from testit"; // testit has 2 columns, id and age
$result = mysql_query($query, $link);
if (!$result) {die( 'Error in SQL: ' . mysql_error());}
// process results using cursor
while ($row = mysql_fetch_array($result))
{
echo "<hr>"; //horizontal line
echo "id: ". $row["id"] . "<br />";
echo "age: " . $row["age"] . "<br />";
}
mysql_free_result ($result);
mysql_close($link); // disconnecting from MySQL
?>
PHP and MySQL
<?php
$link=mysql_connect (“localhost”, “login”, “password”)
mysql_select_db(‘db') or die('Cannot select database');
$query = 'CREATE TABLE contact( '.
'cid INT NOT NULL AUTO_INCREMENT, '.
'cname VARCHAR(20) NOT NULL, '.
'cemail VARCHAR(50) NOT NULL, '.
'csubject VARCHAR(30) NOT NULL, '.
mysql_query($query, $link) or die (‘Cannot create table’);
mysql_close($link);
?>
Access result row using col. name
<?php
$link=mysql_connect (“localhost”, “login”, “password”)
mysql_select_db(‘db') or die('Cannot select database'); $query =
"SELECT ssn, lname FROM employee";
$result = mysql_query($query, $link);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo “SSN :{$row[‘ssn']} <br>" .
“Last : {$row[‘lname']} <br> <br>";
}
// Alterntiavely can use index
// while($row = mysql_fetch_array($result, MYSQL_NUM))
// {
// echo “SSN :{$row[0]} <br>" .
// “Last : {$row[1]} <br><br>";
// }
mysql_close($link);
?>
Forms and input
• Can use HTML to create forms
• Users can input values to use as host
variables in calls to mysql
Our setup
• A machine for us to use PHP and MySQL
• ip address of machine is: 130.160.47.111
• This is a linux machine
– Emacs, vi (I haven’t used this since the ’80s)
• You need to use SSH Secure Shell to Quick
Connect to this machine
• username is 1st
name initial followed by last
name
• E-mail me requesting your password
Our setup
• In order to use your account you must do:
mkdir public_html
chmod 755 public_html/
cd public_html
• Use vi (or whatever) to create new PHP
and HTML files in this directory
Our setup
• Create/save a .php file using an editor
• Sample program:
<? php
Echo “Hello World”
?>
• To run it, from IE, type in ip
address/~yourlogin/filename
MySQL
• To start up MySQL type in:
mysql –u your_login –D your_login –p
It will then prompt you for your password
• You automatically have a db created with
the same name as your login, that is the
–D parameter above
Example html and php
<html>
<head>
</head>
<center>
<!-- The following line results in php code executed after input values in form ->
<form method="post" action="example3.php">
<table>
<tr><td align="left">Dnames</td>
<td><input type="text" name="dname"></td>
</tr>
<tr><td align="left">Lname</td>
<td><input type="text" name="lname" size="15"></td>
</tr>
<tr><colspan="2">
<p align="center">
<input type="submit" value="Enter record">
</td>
</tr>
</table>
</form>
</center>
</html>
Html code
• The previous code uses a form to ask for
input values to a table
• It will execute a php file after input values
in form
• Can use those values in php file, must use
$_POST[‘var_name’]
PHP code
• PHP code places values input from from
into local variables
• Connects to database
• Inserts values into tables
• Prints out values
PHP and MySQL
<?
// This is example3.php used in previous .htm code
$link = mysql_connect("localhost", "svrbsky", “password");
if (!$link) {die('Not connected: '. mysql_error()); }
mysql_select_db(‘svrbsky') or die ('Could not select database');
$dname= $_POST['dname'];
$lname = $_POST['lname'];
$query = "insert into testit2 values ('$dname', '$lname')";
$result = mysql_query($query);
if (!$result) {die('SQL error: ' . mysql_error());}
mysql_close($link);
print "<html><body><center>";
print "<p>You have just entered this record<p>";
print "Dname: $dname<br>";
print "Lname: $lname";
print "</body></html>";
?>
• Won’t this be fun for an assignment?
• Lots of great links on the web to get into
• How to determine what is error?

More Related Content

What's hot (20)

Php basics
Php basicsPhp basics
Php basics
Jamshid Hashimi
 
Html n CSS
Html n CSSHtml n CSS
Html n CSS
Sukrit Gupta
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
Priya Goyal
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
www.netgains.org
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.Net
Hitesh Santani
 
MongoDB Aggregation
MongoDB Aggregation MongoDB Aggregation
MongoDB Aggregation
Amit Ghosh
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
shreesenthil
 
Cascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) helpCascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) help
casestudyhelp
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
Shlomi Komemi
 
Span and Div tags in HTML
Span and Div tags in HTMLSpan and Div tags in HTML
Span and Div tags in HTML
Biswadip Goswami
 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
Edureka!
 
Introduction to web application development
Introduction to web application developmentIntroduction to web application development
Introduction to web application development
Ayyappadhas K B
 
Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using Javascript
Bansari Shah
 
Jquery
JqueryJquery
Jquery
Girish Srivastava
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
Alokin Software Pvt Ltd
 
PHP Syntax & Comments
PHP Syntax & CommentsPHP Syntax & Comments
PHP Syntax & Comments
Sidrah Noor
 
Web forms in ASP.net
Web forms in ASP.netWeb forms in ASP.net
Web forms in ASP.net
Madhuri Kavade
 
Css pseudo-classes
Css pseudo-classesCss pseudo-classes
Css pseudo-classes
Webtech Learning
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servlets
vishal choudhary
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.Net
Hitesh Santani
 
MongoDB Aggregation
MongoDB Aggregation MongoDB Aggregation
MongoDB Aggregation
Amit Ghosh
 
Cascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) helpCascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) help
casestudyhelp
 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
Edureka!
 
Introduction to web application development
Introduction to web application developmentIntroduction to web application development
Introduction to web application development
Ayyappadhas K B
 
Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using Javascript
Bansari Shah
 
PHP Syntax & Comments
PHP Syntax & CommentsPHP Syntax & Comments
PHP Syntax & Comments
Sidrah Noor
 
Session tracking in servlets
Session tracking in servletsSession tracking in servlets
Session tracking in servlets
vishal choudhary
 

Similar to PHP and MySQL (20)

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
 
Php reports sumit
Php reports sumitPhp reports sumit
Php reports sumit
Sumit Biswas
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
aadi Surve
 
Php
PhpPhp
Php
samirlakhanistb
 
Php
PhpPhp
Php
khushbulakhani1
 
Php summary
Php summaryPhp summary
Php summary
Michelle Darling
 
PHP - Intriduction to MySQL And PHP
PHP - Intriduction to MySQL And PHPPHP - Intriduction to MySQL And PHP
PHP - Intriduction to MySQL And PHP
Vibrant Technologies & Computers
 
Sql php-vibrant course-mumbai(1)
Sql php-vibrant course-mumbai(1)Sql php-vibrant course-mumbai(1)
Sql php-vibrant course-mumbai(1)
vibrantuser
 
php
phpphp
php
J.T.A.JONES
 
Php and MySQL Web Development
Php and MySQL Web DevelopmentPhp and MySQL Web Development
Php and MySQL Web Development
w3ondemand
 
Web programming
Web programmingWeb programming
Web programming
Ishucs
 
PHP Hypertext Preprocessor
PHP Hypertext PreprocessorPHP Hypertext Preprocessor
PHP Hypertext Preprocessor
adeel990
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
PHP BASIC PRESENTATION
PHP BASIC PRESENTATIONPHP BASIC PRESENTATION
PHP BASIC PRESENTATION
krutitrivedi
 
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).pptLect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
SenzotaSemakuwa
 
Connecting to my sql using PHP
Connecting to my sql using PHPConnecting to my sql using PHP
Connecting to my sql using PHP
Nisa Soomro
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
shanmukhareddy dasi
 
Lecture1 introduction by okello erick
Lecture1 introduction by okello erickLecture1 introduction by okello erick
Lecture1 introduction by okello erick
okelloerick
 
Php with mysql ppt
Php with mysql pptPhp with mysql ppt
Php with mysql ppt
Rajamanickam Gomathijayam
 
PHP MySQL
PHP MySQLPHP MySQL
PHP MySQL
Md. Sirajus Salayhin
 
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
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
aadi Surve
 
Sql php-vibrant course-mumbai(1)
Sql php-vibrant course-mumbai(1)Sql php-vibrant course-mumbai(1)
Sql php-vibrant course-mumbai(1)
vibrantuser
 
Php and MySQL Web Development
Php and MySQL Web DevelopmentPhp and MySQL Web Development
Php and MySQL Web Development
w3ondemand
 
Web programming
Web programmingWeb programming
Web programming
Ishucs
 
PHP Hypertext Preprocessor
PHP Hypertext PreprocessorPHP Hypertext Preprocessor
PHP Hypertext Preprocessor
adeel990
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
PHP BASIC PRESENTATION
PHP BASIC PRESENTATIONPHP BASIC PRESENTATION
PHP BASIC PRESENTATION
krutitrivedi
 
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).pptLect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
SenzotaSemakuwa
 
Connecting to my sql using PHP
Connecting to my sql using PHPConnecting to my sql using PHP
Connecting to my sql using PHP
Nisa Soomro
 
Lecture1 introduction by okello erick
Lecture1 introduction by okello erickLecture1 introduction by okello erick
Lecture1 introduction by okello erick
okelloerick
 
Ad

More from webhostingguy (20)

File Upload
File UploadFile Upload
File Upload
webhostingguy
 
Running and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test FrameworkRunning and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test Framework
webhostingguy
 
MySQL and memcached Guide
MySQL and memcached GuideMySQL and memcached Guide
MySQL and memcached Guide
webhostingguy
 
Novell® iChain® 2.3
Novell® iChain® 2.3Novell® iChain® 2.3
Novell® iChain® 2.3
webhostingguy
 
Load-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web serversLoad-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web servers
webhostingguy
 
SQL Server 2008 Consolidation
SQL Server 2008 ConsolidationSQL Server 2008 Consolidation
SQL Server 2008 Consolidation
webhostingguy
 
What is mod_perl?
What is mod_perl?What is mod_perl?
What is mod_perl?
webhostingguy
 
What is mod_perl?
What is mod_perl?What is mod_perl?
What is mod_perl?
webhostingguy
 
Master Service Agreement
Master Service AgreementMaster Service Agreement
Master Service Agreement
webhostingguy
 
Notes8
Notes8Notes8
Notes8
webhostingguy
 
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
webhostingguy
 
Managing Diverse IT Infrastructure
Managing Diverse IT InfrastructureManaging Diverse IT Infrastructure
Managing Diverse IT Infrastructure
webhostingguy
 
Web design for business.ppt
Web design for business.pptWeb design for business.ppt
Web design for business.ppt
webhostingguy
 
IT Power Management Strategy
IT Power Management Strategy IT Power Management Strategy
IT Power Management Strategy
webhostingguy
 
Excel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for MerchandisersExcel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for Merchandisers
webhostingguy
 
OLUG_xen.ppt
OLUG_xen.pptOLUG_xen.ppt
OLUG_xen.ppt
webhostingguy
 
Parallels Hosting Products
Parallels Hosting ProductsParallels Hosting Products
Parallels Hosting Products
webhostingguy
 
Microsoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 MbMicrosoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 Mb
webhostingguy
 
Reseller's Guide
Reseller's GuideReseller's Guide
Reseller's Guide
webhostingguy
 
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
webhostingguy
 
Running and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test FrameworkRunning and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test Framework
webhostingguy
 
MySQL and memcached Guide
MySQL and memcached GuideMySQL and memcached Guide
MySQL and memcached Guide
webhostingguy
 
Novell® iChain® 2.3
Novell® iChain® 2.3Novell® iChain® 2.3
Novell® iChain® 2.3
webhostingguy
 
Load-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web serversLoad-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web servers
webhostingguy
 
SQL Server 2008 Consolidation
SQL Server 2008 ConsolidationSQL Server 2008 Consolidation
SQL Server 2008 Consolidation
webhostingguy
 
Master Service Agreement
Master Service AgreementMaster Service Agreement
Master Service Agreement
webhostingguy
 
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
webhostingguy
 
Managing Diverse IT Infrastructure
Managing Diverse IT InfrastructureManaging Diverse IT Infrastructure
Managing Diverse IT Infrastructure
webhostingguy
 
Web design for business.ppt
Web design for business.pptWeb design for business.ppt
Web design for business.ppt
webhostingguy
 
IT Power Management Strategy
IT Power Management Strategy IT Power Management Strategy
IT Power Management Strategy
webhostingguy
 
Excel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for MerchandisersExcel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for Merchandisers
webhostingguy
 
Parallels Hosting Products
Parallels Hosting ProductsParallels Hosting Products
Parallels Hosting Products
webhostingguy
 
Microsoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 MbMicrosoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 Mb
webhostingguy
 
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
webhostingguy
 
Ad

PHP and MySQL

  • 2. PHP • Creates DYNAMIC web pages – HTML traditionally static – Contents regenerated every time visit or reload site • (e.g. can include current time) • PHP is a scripting language – Interpreted, not converted to binary executable files – (Dialogue for play interpreted by actors) – Strong at communicating with program components written in other languages • E.g. can embed PHP statements within HTML
  • 3. PHP • Written as a set of CGI binaries in C in 1994 by R. Lerdorf – Created to display resume and collect data about page traffic, e.g. dynamic web pages – Personal Home Page tools publicly released 1995 – In 1998 became PHP: Hypertext Preprocessor • PHP parser with web server and web browser, model similar to MS ASP.NET, Sun JavaServer Pages
  • 4. PHP • Used mainly in server-side scripting – Can be used from command line interface – Standalone graphical applications • Takes input from a file or stream containing text and PHP instructions • Outputs stream of data for display • PHP 4 – parser compiles input to produce bytecode – Zend engine (better performance than interpreted PHP 3) • PHP 5 – robust support for OO programming, better support for MySQL, support for SQLite, performance enhancements
  • 5. PHP - specifics • Delimiters: <?php ?> or just <? ?> • PHP parses code within delimiters • Code outside delimiter sent to output, not parsed • Block comments /* */ • Inline comments // #
  • 6. PHP vs. C++ • Similarities: – Compiled Language – Syntax nearly the same (For/While/If) – Requires semicolons after each statement ; – Assignment is right to left ($num = 56;) – Object-Oriented (Class support, inheritance, virtuals, polymorphism) – Functions! – Types are nearly the same (booleans, integers, strings, etc.)
  • 7. PHP Versus C++ • Differences: – Variables begin with $ sign ($name = “John Doe”;) – No explicit declaration of variable types – Introduction of “lazy” functions (foreach, explode, mail) – No Function Overloading – “Hidden” functions-within-a-function – Compiled/interpreted during every page load – Documented! – Echo for output
  • 8. PHP Versus C++ • Web Specific: – Cookies and “Sessions” – Dynamic HTML based on user-defined logic – Interact and process a form’s action – Process URL Parameters – Easy Database Integration – Cross-Site-Scripting (XSS) security hacks - taken care of by PHP 5 • Allows code injection by web users into web pages viewed by other users (e.g. phishing attacks)
  • 9. Introducing/Review HTML • Hyper Text Markup Language: – Paired by angled brackets like XML (Ex. <font> </font>) – Can use a “WYSIWYG” (what you see is what you get) program such as FrontPage or Dreamweaver for development – Dynamic web languages such as PHP simply produces HTML
  • 10. MySQL • MySQL queries same as SQL in Oracle • Except it’s freeware! • Has many of the same capabilities as traditional DBMSs – Multi-user, triggers, cursors, etc. – Doesn’t get performance advantages
  • 11. MySQL commands mysql> CREATE TABLE table_name … INSERT Into table_name … mysql> LOAD DATA LOCAL INFILE “file_name” INTO TABLE table_name; mysql> file_name (containing a query) mysql> SELECT … FROM … WHERE … mysql> UPDATE … mysql> DELETE …
  • 12. MySQL commands mysql> SHOW databases; mysql> USE db_name; mysql> SHOW tables; mysql> DESCRIBE table_name; mysql> create table … mysql> insert into table values (… mysql> select * from table_name;
  • 13. Some php mysql functions • Mysql_connect (“localhost”, “login”, “password”) • Mysql_select_db (‘db_name’, $link_id) • mysql_query (string [, resource $link_id]) – Executes a query, place result in variable, like a cursor • mysql_error ( ) – Returns error message from previous sql operation • mysql_fetch_array ($result, how) – Traverses through cursor of query result – How is either mysql_assoc (use col. names) – Or mysql_num (use index number) or mysql_both • Mysql_num_fields
  • 14. PHP In Action <? echo "Welcome to Vrbsky's DB"; // Connect to MySQL $link = mysql_connect("localhost", "svrbsky", “password"); if (!$link) {die('Not connected: '. mysql_error()); } // see if connected // Select DB will use $dbselected = mysql_select_db('cs457db', $link); // you may not have to do this mysql_select_db('cs457db') or die ('Could not select database'); // see if worked // Now the query $query = "Select * from testit"; // testit has 2 columns, id and age $result = mysql_query($query, $link); if (!$result) {die( 'Error in SQL: ' . mysql_error());} // process results using cursor while ($row = mysql_fetch_array($result)) { echo "<hr>"; //horizontal line echo "id: ". $row["id"] . "<br />"; echo "age: " . $row["age"] . "<br />"; } mysql_free_result ($result); mysql_close($link); // disconnecting from MySQL ?>
  • 15. PHP and MySQL <?php $link=mysql_connect (“localhost”, “login”, “password”) mysql_select_db(‘db') or die('Cannot select database'); $query = 'CREATE TABLE contact( '. 'cid INT NOT NULL AUTO_INCREMENT, '. 'cname VARCHAR(20) NOT NULL, '. 'cemail VARCHAR(50) NOT NULL, '. 'csubject VARCHAR(30) NOT NULL, '. mysql_query($query, $link) or die (‘Cannot create table’); mysql_close($link); ?>
  • 16. Access result row using col. name <?php $link=mysql_connect (“localhost”, “login”, “password”) mysql_select_db(‘db') or die('Cannot select database'); $query = "SELECT ssn, lname FROM employee"; $result = mysql_query($query, $link); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo “SSN :{$row[‘ssn']} <br>" . “Last : {$row[‘lname']} <br> <br>"; } // Alterntiavely can use index // while($row = mysql_fetch_array($result, MYSQL_NUM)) // { // echo “SSN :{$row[0]} <br>" . // “Last : {$row[1]} <br><br>"; // } mysql_close($link); ?>
  • 17. Forms and input • Can use HTML to create forms • Users can input values to use as host variables in calls to mysql
  • 18. Our setup • A machine for us to use PHP and MySQL • ip address of machine is: 130.160.47.111 • This is a linux machine – Emacs, vi (I haven’t used this since the ’80s) • You need to use SSH Secure Shell to Quick Connect to this machine • username is 1st name initial followed by last name • E-mail me requesting your password
  • 19. Our setup • In order to use your account you must do: mkdir public_html chmod 755 public_html/ cd public_html • Use vi (or whatever) to create new PHP and HTML files in this directory
  • 20. Our setup • Create/save a .php file using an editor • Sample program: <? php Echo “Hello World” ?> • To run it, from IE, type in ip address/~yourlogin/filename
  • 21. MySQL • To start up MySQL type in: mysql –u your_login –D your_login –p It will then prompt you for your password • You automatically have a db created with the same name as your login, that is the –D parameter above
  • 22. Example html and php <html> <head> </head> <center> <!-- The following line results in php code executed after input values in form -> <form method="post" action="example3.php"> <table> <tr><td align="left">Dnames</td> <td><input type="text" name="dname"></td> </tr> <tr><td align="left">Lname</td> <td><input type="text" name="lname" size="15"></td> </tr> <tr><colspan="2"> <p align="center"> <input type="submit" value="Enter record"> </td> </tr> </table> </form> </center> </html>
  • 23. Html code • The previous code uses a form to ask for input values to a table • It will execute a php file after input values in form • Can use those values in php file, must use $_POST[‘var_name’]
  • 24. PHP code • PHP code places values input from from into local variables • Connects to database • Inserts values into tables • Prints out values
  • 25. PHP and MySQL <? // This is example3.php used in previous .htm code $link = mysql_connect("localhost", "svrbsky", “password"); if (!$link) {die('Not connected: '. mysql_error()); } mysql_select_db(‘svrbsky') or die ('Could not select database'); $dname= $_POST['dname']; $lname = $_POST['lname']; $query = "insert into testit2 values ('$dname', '$lname')"; $result = mysql_query($query); if (!$result) {die('SQL error: ' . mysql_error());} mysql_close($link); print "<html><body><center>"; print "<p>You have just entered this record<p>"; print "Dname: $dname<br>"; print "Lname: $lname"; print "</body></html>"; ?>
  • 26. • Won’t this be fun for an assignment? • Lots of great links on the web to get into • How to determine what is error?