SlideShare ist ein Scribd-Unternehmen logo
1 von 26
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?

Weitere ähnliche Inhalte

Was ist angesagt?

Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
alexjones89
 
Introduction to Web Programming - first course
Introduction to Web Programming - first courseIntroduction to Web Programming - first course
Introduction to Web Programming - first course
Vlad Posea
 

Was ist angesagt? (20)

Php mysql
Php mysqlPhp mysql
Php mysql
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Php Ppt
Php PptPhp Ppt
Php Ppt
 
File Uploading in PHP
File Uploading in PHPFile Uploading in PHP
File Uploading in PHP
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
 
Php array
Php arrayPhp array
Php array
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
Files in php
Files in phpFiles in php
Files in php
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
04 Handling Exceptions
04 Handling Exceptions04 Handling Exceptions
04 Handling Exceptions
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Introduction to Web Programming - first course
Introduction to Web Programming - first courseIntroduction to Web Programming - first course
Introduction to Web Programming - first course
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
 

Ähnlich wie PHP and MySQL

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
 
6 3 tier architecture php
6 3 tier architecture php6 3 tier architecture php
6 3 tier architecture php
cefour
 

Ähnlich wie PHP and MySQL (20)

Amp and higher computing science
Amp and higher computing scienceAmp and higher computing science
Amp and higher computing science
 
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 ...
 
Php reports sumit
Php reports sumitPhp reports sumit
Php reports sumit
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
6 3 tier architecture php
6 3 tier architecture php6 3 tier architecture php
6 3 tier architecture php
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentation
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Server
 
phpwebdev.ppt
phpwebdev.pptphpwebdev.ppt
phpwebdev.ppt
 
Php intro
Php introPhp intro
Php intro
 
Php intro
Php introPhp intro
Php intro
 
Php intro
Php introPhp intro
Php intro
 
PHP Hypertext Preprocessor
PHP Hypertext PreprocessorPHP Hypertext Preprocessor
PHP Hypertext Preprocessor
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
 
Php with mysql ppt
Php with mysql pptPhp with mysql ppt
Php with mysql ppt
 
Knolx session
Knolx sessionKnolx session
Knolx session
 
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
 
PHP presentation - Com 585
PHP presentation - Com 585PHP presentation - Com 585
PHP presentation - Com 585
 
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
 

Mehr von 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
 

Mehr von webhostingguy (20)

File Upload
File UploadFile Upload
File Upload
 
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
 
MySQL and memcached Guide
MySQL and memcached GuideMySQL and memcached Guide
MySQL and memcached Guide
 
Novell® iChain® 2.3
Novell® iChain® 2.3Novell® iChain® 2.3
Novell® iChain® 2.3
 
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
 
SQL Server 2008 Consolidation
SQL Server 2008 ConsolidationSQL Server 2008 Consolidation
SQL Server 2008 Consolidation
 
What is mod_perl?
What is mod_perl?What is mod_perl?
What is mod_perl?
 
What is mod_perl?
What is mod_perl?What is mod_perl?
What is mod_perl?
 
Master Service Agreement
Master Service AgreementMaster Service Agreement
Master Service Agreement
 
Notes8
Notes8Notes8
Notes8
 
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 ...
 
Managing Diverse IT Infrastructure
Managing Diverse IT InfrastructureManaging Diverse IT Infrastructure
Managing Diverse IT Infrastructure
 
Web design for business.ppt
Web design for business.pptWeb design for business.ppt
Web design for business.ppt
 
IT Power Management Strategy
IT Power Management Strategy IT Power Management Strategy
IT Power Management Strategy
 
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
 
OLUG_xen.ppt
OLUG_xen.pptOLUG_xen.ppt
OLUG_xen.ppt
 
Parallels Hosting Products
Parallels Hosting ProductsParallels Hosting Products
Parallels Hosting Products
 
Microsoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 MbMicrosoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 Mb
 
Reseller's Guide
Reseller's GuideReseller's Guide
Reseller's Guide
 
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 ...
 

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?