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>
</div><div id=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

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?