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?
Ad

More Related Content

What's hot (20)

Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with php
Muhamad Al Imran
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
Ganga Ram
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
Michael Pirnat
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
之宇 趙
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
Larry Cai
 
Javascript
JavascriptJavascript
Javascript
Sun Technlogies
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
ElangovanTechNotesET
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
teach4uin
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
Taha Malampatti
 
4.2 PHP Function
4.2 PHP Function4.2 PHP Function
4.2 PHP Function
Jalpesh Vasa
 
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
Mallikarjuna G D
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
 
Basic introduction to html and php tags
Basic introduction to html and php tagsBasic introduction to html and php tags
Basic introduction to html and php tags
Kailash Kumar
 
Files in php
Files in phpFiles in php
Files in php
sana mateen
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
Bala Kumar
 
Get method and post method
Get method and post methodGet method and post method
Get method and post method
baabtra.com - No. 1 supplier of quality freshers
 
php
phpphp
php
ajeetjhajharia
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
sentayehu
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
Ganga Ram
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
Michael Pirnat
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
之宇 趙
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
Larry Cai
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
ElangovanTechNotesET
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
teach4uin
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
 
Basic introduction to html and php tags
Basic introduction to html and php tagsBasic introduction to html and php tags
Basic introduction to html and php tags
Kailash Kumar
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
Bala Kumar
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
sentayehu
 

Similar to PHP and MySQL (20)

Amp and higher computing science
Amp and higher computing scienceAmp and higher computing science
Amp and higher computing science
Charlie Love
 
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
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
Wildan Maulana
 
6 3 tier architecture php
6 3 tier architecture php6 3 tier architecture php
6 3 tier architecture php
cefour
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentation
Annujj Agrawaal
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
Alokin Software Pvt Ltd
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
Zeeshan Ahmed
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Server
hendrikvb
 
phpwebdev.ppt
phpwebdev.pptphpwebdev.ppt
phpwebdev.ppt
rawaccess
 
Php intro
Php introPhp intro
Php intro
Jennie Gajjar
 
Php intro
Php introPhp intro
Php intro
Jennie Gajjar
 
Php intro
Php introPhp intro
Php intro
Jennie Gajjar
 
PHP Hypertext Preprocessor
PHP Hypertext PreprocessorPHP Hypertext Preprocessor
PHP Hypertext Preprocessor
adeel990
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
Joram Salinas
 
Php with mysql ppt
Php with mysql pptPhp with mysql ppt
Php with mysql ppt
Rajamanickam Gomathijayam
 
Knolx session
Knolx sessionKnolx session
Knolx session
Knoldus Inc.
 
Php &amp; my sql - how do pdo, mysq-li, and x devapi do what they do
Php &amp; my sql  - how do pdo, mysq-li, and x devapi do what they doPhp &amp; my sql  - how do pdo, mysq-li, and x devapi do what they do
Php &amp; my sql - how do pdo, mysq-li, and x devapi do what they do
Dave Stokes
 
PHP presentation - Com 585
PHP presentation - Com 585PHP presentation - Com 585
PHP presentation - Com 585
jstout007
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
rICh morrow
 
Amp and higher computing science
Amp and higher computing scienceAmp and higher computing science
Amp and higher computing science
Charlie Love
 
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
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
Wildan Maulana
 
6 3 tier architecture php
6 3 tier architecture php6 3 tier architecture php
6 3 tier architecture php
cefour
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentation
Annujj Agrawaal
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Server
hendrikvb
 
phpwebdev.ppt
phpwebdev.pptphpwebdev.ppt
phpwebdev.ppt
rawaccess
 
PHP Hypertext Preprocessor
PHP Hypertext PreprocessorPHP Hypertext Preprocessor
PHP Hypertext Preprocessor
adeel990
 
Php &amp; my sql - how do pdo, mysq-li, and x devapi do what they do
Php &amp; my sql  - how do pdo, mysq-li, and x devapi do what they doPhp &amp; my sql  - how do pdo, mysq-li, and x devapi do what they do
Php &amp; my sql - how do pdo, mysq-li, and x devapi do what they do
Dave Stokes
 
PHP presentation - Com 585
PHP presentation - Com 585PHP presentation - Com 585
PHP presentation - Com 585
jstout007
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
rICh morrow
 
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?
  翻译: