SlideShare a Scribd company logo
PHP and MySQL
PHP Written as a set of CGI binaries in C in 1994 by R. Lerdorf Didn’t just want to post his resume Created PHP 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 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  a programming language that controls a software application (program is independent of any other application) Strong at communicating with program components written in other languages E.g. can embed PHP statements within HTML Script like a dialogue for play interpreted by actors PHP parser with web server and web browser, model similar to MS ASP.NET, Sun JavaServer Pages
PHP Takes input from a file or stream containing text and PHP instructions Outputs stream of data for display PHP originally interpreted, not converted to binary executable files PHP 4 – parser compiles input to produce bytecode (semi-compiled) – Zend engine (better performance than interpreted  PHP 3) PHP 5 – robust support for OO programming, better support for MySQL, support for SQLite, performance enhancements SQLite – ACID compliant embedded relational DB contained in small C programming library.  Source code in public domain.  SQLite library is linked in and part of application program, uses simple function calls, reducing latency.  Entire DB stored as a single file on a host machine.
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: 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 code injection by web users into web pages viewed by other users (e.g. phishing attacks)
Sample code <?php  // do not put a space between ? and php Echo “Hello World”;  // can use either “ or ‘ ?> To run this, only need to specify a link to this program http://vrbsky-linux-1.cs.ua.edu/svrbsky/test.php
Easy Database Integration  For example: MySQL
MySQL MySQL is a relational DBMS Has many of the same capabilities as traditional DBMSs (newest releases) MySQL queries mostly the same as SQL in Oracle (subsidiary of Sun) Popular for web databases It’s freeware!
You can connect to MySQL directly OR You can connect to MySQL through .php
MySQL commands Can connect directly to MySQL: mysql> SHOW databases; mysql> USE db_name;  // must specify this each time mysql> SHOW tables; mysql> DESCRIBE table_name; mysql> create table … mysql> insert into table values (… mysql> select * from table_name; mysql> delete … mysql> update
MySQL commands mysql> LOAD DATA LOCAL INFILE “file_name” INTO TABLE table_name; mysql> file_name (containing a query)
You can connect to MySQL directly OR You can connect to MySQL through .php
Some php mysql functions Connecting to MySQL through PHP 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 Resource specifies a connection, otherwise last connection opened used 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 ( $result) Returns number of columns in table (fields in recordset)
PHP and MySQL – ex1 <?php $link=mysql_connect (&quot;localhost&quot;, &quot;vrbsky&quot;, “password&quot;); mysql_select_db('vrbsky') or die('Cannot select database'); $query = 'CREATE TABLE contact( '. 'cid INT NOT NULL, '. 'cname VARCHAR(20) NOT NULL, '. 'cemail VARCHAR(50) NOT NULL, '. 'csubject VARCHAR(30) NOT NULL, '. 'constraint pk PRIMARY KEY (cid) )' ; $result = mysql_query($query, $link); if(!$result) {die( 'Error in SQL: ' . mysql_error());} mysql_close($link); ?>
Example ex2 <?php echo &quot;Welcome to Vrbsky's DB&quot;; // Connect to MySQL $link = mysql_connect(&quot;localhost&quot;, &quot;vrbsky&quot;, “password&quot;); if (!$link) {die('Not connected: '. mysql_error()); }  // see if connected // Select DB will use mysql_select_db('vrbsky') or die ('Could not select database');  // see if worked // Now the query $query = &quot;Select * from testit&quot;;  // 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 &quot;<hr>&quot;;  //horizontal line echo &quot;id: &quot;. $row[&quot;id&quot;] . &quot;<br />&quot;; echo &quot;age: &quot; . $row[&quot;age&quot;] .  &quot;<br />&quot;; } mysql_free_result ($result); mysql_close($link);  // disconnecting from MySQL ?>
http://vrbsky-linux-1.cs.ua.edu/svrbsky/ex1.php http://vrbsky-linux-1.cs.ua.edu/svrbsky/ex2.php
Accessing result rows <?php $link=mysql_connect (&quot;localhost&quot;, &quot;vrbsky&quot;, “password&quot;); mysql_select_db('vrbsky') or die('Cannot select database');  $query = &quot;SELECT ssn, lname FROM employee&quot;; $result = mysql_query($query, $link); //Using column name while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo &quot;SSN :{$row['ssn']} <br>&quot; . &quot;Last : {$row['lname']} <br> <br>&quot;; }  //  Using an index // while($row = mysql_fetch_array($result, MYSQL_NUM)) // { //  echo &quot;SSN :{$row[0]} <br>&quot; . //  &quot;Last : {$row[1]} <br><br>&quot;; // } 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
HTML code The following code uses a form to ask for input values to a table It will execute a php file after values are input in the form To use those values in php file, must use $_POST[‘var_name’]
$_POST function < form method=&quot;post&quot; action=&quot;example.php&quot;> variables from a form will be placed into an array $_POST Index into array is form data name Info sent from form invisible  With POST no limits on the amount of info to send Different from $_GET function where Info sent is displayed in browser’s address bar Max 100 characters
HTML and PHP and MYSQL ex3.html <html> <head> </head> <center> <!--  The following line results in php code executed after input values in form -> <form method=&quot;post&quot; action=&quot;example3.php&quot;> <table> <tr><td align=&quot;left&quot;>ID</td> <td><input type=&quot;text&quot; name=&quot;id&quot;></td> </tr> <tr><td align=&quot;left&quot;>Age</td> <td><input type=&quot;text&quot; name=&quot;age&quot; size=&quot;15&quot;></td> </tr> <tr><colspan=&quot;2&quot;> <p align=&quot;center&quot;> <input type=&quot;submit&quot; value=&quot;Enter record&quot;> </td> </tr> </table> </form> </center> </html>
PHP code PHP code places values input from form into local variables Connects to database Inserts values into tables Prints out values
example3.php <?php //  This is example3.php used in previous .htm code $link = mysql_connect(&quot;localhost&quot;, &quot;svrbsky&quot;, “cwid&quot;); if (!$link) {die('Not connected: '. mysql_error()); } mysql_select_db('vrbsky') or die ('Could not select database'); $id= $_POST['id']; $age = $_POST['age']; $query = &quot;insert into  testit values ('$id', '$age')&quot;; $result = mysql_query($query); if (!$result) {die('SQL error: ' . mysql_error());} mysql_close($link); print &quot;<html><body><center>&quot;; print &quot;<p>You have just entered this record<p>&quot;; print &quot;ID:  $id<br>&quot;; print &quot;Age: $age&quot;; print &quot;</body></html>&quot;; ?>
http://vrbsky-linux-1.cs.ua.edu/svrbsky/ex3.html
Example HTML and PHP ex4.html <html> <body> <center> <form method=&quot;post&quot; action=&quot;example4.php&quot;> <!-- places values in associative array called $_POST --> <font size=&quot;18&quot;>Complete the Select Statement</font><br> Select <input type=&quot;text&quot; name=&quot;select&quot; size=&quot;60&quot; value=&quot;  ;&quot; ><br> <input type=&quot;hidden&quot; name=&quot;_query_form2&quot; value=&quot;1&quot;> <input type=&quot;submit&quot; nvalue=&quot;Get Query&quot;></form> <table border=&quot;1&quot;> </table></center></body></html>
example4.php code segment <?php  //This is example4.php referenced in previous .html code $link = mysql_connect(&quot;localhost&quot;, &quot;svrbsky&quot;, “cwid&quot;); if(!$link) { die('Not connected: '.mysql_error);} mysql_select_db('vrbsky'); // isset  tests if the value of the variable is set if(isset($_POST['_query_form2']) && isset($_POST['select'])) { $select = 'select'.$_POST['select']; $result = mysql_query($select, $link); if(!$result) { echo mysql_error();  } else { while($row = mysql_fetch_array($result, MYSQL_NUM)) { echo &quot;<hr>&quot;;  // horizontal line echo &quot;<tr>&quot;; for($count = 0; $count < 10; $count++)  { if(isset($row[$count])) echo &quot;  <td>{$row[$count]}</td>&quot;; if(!isset($row[$count]) && isset($row[++$count])) { echo &quot;<td></td>&quot;; $count--; } } echo &quot;</tr>&quot;; } } } ?>
http://vrbsky-linux-1.cs.ua.edu/svrbsky/ex4.html
Our Setup This this link to our machine: Vrbsky-linux-1.cs.ua.edu  130.160.68.71
Our setup A machine for us to use PHP and MySQL address of machine is: Vrbsky-linux-1.cs.ua.edu or 130.160.68.71 This is a linux machine Emacs, vi (I haven’t used this since the ’80s) username is 1 st  name initial followed by last name with a password of CWID Ex. John Doe username is:  jdoe You need to use SSH Secure Shell to directly Quick Connect to this machine
Our setup Use vi (or whatever) to create new PHP and HTML files OR   you can just edit files locally then use SSH file transfer to this machine
Our Setup To run MySQL directly To start up MySQL type in: mysql –u  your_login  –p It will then prompt you for  your password You must create a db created with the same name as your login using: create database  your_login The next time you start up MySQL type in: mysql –u  your_login  –D  your_login  –p where –D is you database
Our setup To use MySQL through PHP Create/save a .php file using an editor Make sure the file is on the lamp.cs.ua.edu machine in the root directory Sample program: <?php Echo “Hello World”; ?> To run it, from IE, type in:  ip address/ yourlogin /filename 130.160.47.52/vrbsky/Hello.php  or lamp.cs.ua.edu/vrbsky/Hello.php
Won’t this be fun for an assignment? Lots of great links on the web to get into Disadvantage:  How to determine what is error?

More Related Content

What's hot (20)

PPT
PHP Workshop Notes
Pamela Fox
 
PPT
Short Intro to PHP and MySQL
Jussi Pohjolainen
 
PDF
Introduction to PHP
Bradley Holt
 
PDF
PHP and Mysql
Sankhadeep Roy
 
DOC
Creating a Simple PHP and MySQL-Based Login System
Azharul Haque Shohan
 
PPT
PHP POWERPOINT SLIDES
Ismail Mukiibi
 
PPTX
PHP FUNCTIONS
Zeeshan Ahmed
 
PPTX
PHP Function
Reber Novanta
 
ODP
PHP BASIC PRESENTATION
krutitrivedi
 
PPT
New: Two Methods of Installing Drupal on Windows XP with XAMPP
Rupesh Kumar
 
PPT
Php mysql
Manish Jain
 
PPT
05 File Handling Upload Mysql
Geshan Manandhar
 
PPTX
PHP for hacks
Tom Praison Praison
 
ODP
Database Connection With Mysql
Harit Kothari
 
PPTX
Introduction to PHP
Collaboration Technologies
 
PPTX
Phphacku iitd
Sorabh Jain
 
PPT
Intro to PHP
Sandy Smith
 
PPT
PHP Tutorials
Yuriy Krapivko
 
PPT
MYSQL - PHP Database Connectivity
V.V.Vanniaperumal College for Women
 
PDF
New Features in PHP 5.3
Bradley Holt
 
PHP Workshop Notes
Pamela Fox
 
Short Intro to PHP and MySQL
Jussi Pohjolainen
 
Introduction to PHP
Bradley Holt
 
PHP and Mysql
Sankhadeep Roy
 
Creating a Simple PHP and MySQL-Based Login System
Azharul Haque Shohan
 
PHP POWERPOINT SLIDES
Ismail Mukiibi
 
PHP FUNCTIONS
Zeeshan Ahmed
 
PHP Function
Reber Novanta
 
PHP BASIC PRESENTATION
krutitrivedi
 
New: Two Methods of Installing Drupal on Windows XP with XAMPP
Rupesh Kumar
 
Php mysql
Manish Jain
 
05 File Handling Upload Mysql
Geshan Manandhar
 
PHP for hacks
Tom Praison Praison
 
Database Connection With Mysql
Harit Kothari
 
Introduction to PHP
Collaboration Technologies
 
Phphacku iitd
Sorabh Jain
 
Intro to PHP
Sandy Smith
 
PHP Tutorials
Yuriy Krapivko
 
MYSQL - PHP Database Connectivity
V.V.Vanniaperumal College for Women
 
New Features in PHP 5.3
Bradley Holt
 

Viewers also liked (20)

PPTX
Mail server on linux
Roshni17
 
PDF
tybsc it sem 5 Linux administration notes of unit 1,2,3,4,5,6 version 3
WE-IT TUTORIALS
 
PPTX
Loops PHP 04
mohamedsaad24
 
PDF
Php introduction
krishnapriya Tadepalli
 
PDF
Configure Webserver & SSL secure & redirect in SuSE Linux Enterprise
Tola LENG
 
PDF
Configure active directory &amp; trust domain
Tola LENG
 
TXT
Advance C++notes
Rajiv Gupta
 
PPT
Map.ppt
webhostingguy
 
DOCX
DNS windows server(2008R2) & linux(SLES 11)
Tola LENG
 
PDF
Network Diagram
Jake Wactor
 
PDF
Install linux suse(sless11)
Tola LENG
 
PDF
Configure Proxy and Firewall (Iptables)
Tola LENG
 
PDF
Configure proxy firewall on SuSE Linux Enterprise Server 11
Tola LENG
 
PDF
jsf2 Notes
Rajiv Gupta
 
PDF
Java Logging discussion Log4j,Slf4j
Rajiv Gupta
 
DOCX
Tola.leng sa nagios
Tola LENG
 
DOCX
How to be a good presentor by tola
Tola LENG
 
PDF
Struts2 notes
Rajiv Gupta
 
PDF
Ansible automation tool with modules
mohamedmoharam
 
TXT
Jsp Notes
Rajiv Gupta
 
Mail server on linux
Roshni17
 
tybsc it sem 5 Linux administration notes of unit 1,2,3,4,5,6 version 3
WE-IT TUTORIALS
 
Loops PHP 04
mohamedsaad24
 
Php introduction
krishnapriya Tadepalli
 
Configure Webserver & SSL secure & redirect in SuSE Linux Enterprise
Tola LENG
 
Configure active directory &amp; trust domain
Tola LENG
 
Advance C++notes
Rajiv Gupta
 
Map.ppt
webhostingguy
 
DNS windows server(2008R2) & linux(SLES 11)
Tola LENG
 
Network Diagram
Jake Wactor
 
Install linux suse(sless11)
Tola LENG
 
Configure Proxy and Firewall (Iptables)
Tola LENG
 
Configure proxy firewall on SuSE Linux Enterprise Server 11
Tola LENG
 
jsf2 Notes
Rajiv Gupta
 
Java Logging discussion Log4j,Slf4j
Rajiv Gupta
 
Tola.leng sa nagios
Tola LENG
 
How to be a good presentor by tola
Tola LENG
 
Struts2 notes
Rajiv Gupta
 
Ansible automation tool with modules
mohamedmoharam
 
Jsp Notes
Rajiv Gupta
 
Ad

Similar to PHP and MySQL PHP Written as a set of CGI binaries in C in ... (20)

PPT
Open Source Package Php Mysql 1228203701094763 9
isadorta
 
PPT
Open Source Package PHP & MySQL
kalaisai
 
PPT
PHP MySQL
Md. Sirajus Salayhin
 
PPT
Building an e:commerce site with PHP
webhostingguy
 
PDF
Php summary
Michelle Darling
 
PPTX
php
J.T.A.JONES
 
PPT
P H P Part I I, By Kian
phelios
 
PPTX
Learn PHP Lacture2
ADARSH BHATT
 
PPT
Intro to php
Sp Singh
 
PPT
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
SenzotaSemakuwa
 
PPTX
Php reports sumit
Sumit Biswas
 
PPT
Php Training
adfa
 
PPT
Php and MySQL Web Development
w3ondemand
 
PPT
IT Club @ NCP - PHP Workshop May 10, 2011
IT Club GTA
 
PPTX
Quick beginner to Lower-Advanced guide/tutorial in PHP
Sanju Sony Kurian
 
PPT
Babitha5.php
banubabitha
 
Open Source Package Php Mysql 1228203701094763 9
isadorta
 
Open Source Package PHP & MySQL
kalaisai
 
Building an e:commerce site with PHP
webhostingguy
 
Php summary
Michelle Darling
 
P H P Part I I, By Kian
phelios
 
Learn PHP Lacture2
ADARSH BHATT
 
Intro to php
Sp Singh
 
Lect_04b_PhpMysqlKEY PERFORMANCE INDICATOR FOR ICT-UNIT (new).ppt
SenzotaSemakuwa
 
Php reports sumit
Sumit Biswas
 
Php Training
adfa
 
Php and MySQL Web Development
w3ondemand
 
IT Club @ NCP - PHP Workshop May 10, 2011
IT Club GTA
 
Quick beginner to Lower-Advanced guide/tutorial in PHP
Sanju Sony Kurian
 
Babitha5.php
banubabitha
 
Ad

More from webhostingguy (20)

PDF
Running and Developing Tests with the Apache::Test Framework
webhostingguy
 
PDF
MySQL and memcached Guide
webhostingguy
 
PPT
Novell® iChain® 2.3
webhostingguy
 
PDF
Load-balancing web servers Load-balancing web servers
webhostingguy
 
PDF
SQL Server 2008 Consolidation
webhostingguy
 
PDF
What is mod_perl?
webhostingguy
 
PDF
What is mod_perl?
webhostingguy
 
PDF
Master Service Agreement
webhostingguy
 
PPT
Notes8
webhostingguy
 
PDF
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
webhostingguy
 
PPT
Managing Diverse IT Infrastructure
webhostingguy
 
PPT
Web design for business.ppt
webhostingguy
 
PPS
IT Power Management Strategy
webhostingguy
 
PPS
Excel and SQL Quick Tricks for Merchandisers
webhostingguy
 
PPT
OLUG_xen.ppt
webhostingguy
 
PPT
Parallels Hosting Products
webhostingguy
 
PPT
Microsoft PowerPoint presentation 2.175 Mb
webhostingguy
 
PDF
Reseller's Guide
webhostingguy
 
PDF
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
webhostingguy
 
PDF
Getting Started Guide
webhostingguy
 
Running and Developing Tests with the Apache::Test Framework
webhostingguy
 
MySQL and memcached Guide
webhostingguy
 
Novell® iChain® 2.3
webhostingguy
 
Load-balancing web servers Load-balancing web servers
webhostingguy
 
SQL Server 2008 Consolidation
webhostingguy
 
What is mod_perl?
webhostingguy
 
What is mod_perl?
webhostingguy
 
Master Service Agreement
webhostingguy
 
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
webhostingguy
 
Managing Diverse IT Infrastructure
webhostingguy
 
Web design for business.ppt
webhostingguy
 
IT Power Management Strategy
webhostingguy
 
Excel and SQL Quick Tricks for Merchandisers
webhostingguy
 
OLUG_xen.ppt
webhostingguy
 
Parallels Hosting Products
webhostingguy
 
Microsoft PowerPoint presentation 2.175 Mb
webhostingguy
 
Reseller's Guide
webhostingguy
 
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
webhostingguy
 
Getting Started Guide
webhostingguy
 

PHP and MySQL PHP Written as a set of CGI binaries in C in ...

  • 2. PHP Written as a set of CGI binaries in C in 1994 by R. Lerdorf Didn’t just want to post his resume Created PHP 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
  • 3. 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 a programming language that controls a software application (program is independent of any other application) Strong at communicating with program components written in other languages E.g. can embed PHP statements within HTML Script like a dialogue for play interpreted by actors PHP parser with web server and web browser, model similar to MS ASP.NET, Sun JavaServer Pages
  • 4. PHP Takes input from a file or stream containing text and PHP instructions Outputs stream of data for display PHP originally interpreted, not converted to binary executable files PHP 4 – parser compiles input to produce bytecode (semi-compiled) – Zend engine (better performance than interpreted PHP 3) PHP 5 – robust support for OO programming, better support for MySQL, support for SQLite, performance enhancements SQLite – ACID compliant embedded relational DB contained in small C programming library. Source code in public domain. SQLite library is linked in and part of application program, uses simple function calls, reducing latency. Entire DB stored as a single file on a host machine.
  • 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: 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 code injection by web users into web pages viewed by other users (e.g. phishing attacks)
  • 9. Sample code <?php // do not put a space between ? and php Echo “Hello World”; // can use either “ or ‘ ?> To run this, only need to specify a link to this program http://vrbsky-linux-1.cs.ua.edu/svrbsky/test.php
  • 10. Easy Database Integration For example: MySQL
  • 11. MySQL MySQL is a relational DBMS Has many of the same capabilities as traditional DBMSs (newest releases) MySQL queries mostly the same as SQL in Oracle (subsidiary of Sun) Popular for web databases It’s freeware!
  • 12. You can connect to MySQL directly OR You can connect to MySQL through .php
  • 13. MySQL commands Can connect directly to MySQL: mysql> SHOW databases; mysql> USE db_name; // must specify this each time mysql> SHOW tables; mysql> DESCRIBE table_name; mysql> create table … mysql> insert into table values (… mysql> select * from table_name; mysql> delete … mysql> update
  • 14. MySQL commands mysql> LOAD DATA LOCAL INFILE “file_name” INTO TABLE table_name; mysql> file_name (containing a query)
  • 15. You can connect to MySQL directly OR You can connect to MySQL through .php
  • 16. Some php mysql functions Connecting to MySQL through PHP 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 Resource specifies a connection, otherwise last connection opened used 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 ( $result) Returns number of columns in table (fields in recordset)
  • 17. PHP and MySQL – ex1 <?php $link=mysql_connect (&quot;localhost&quot;, &quot;vrbsky&quot;, “password&quot;); mysql_select_db('vrbsky') or die('Cannot select database'); $query = 'CREATE TABLE contact( '. 'cid INT NOT NULL, '. 'cname VARCHAR(20) NOT NULL, '. 'cemail VARCHAR(50) NOT NULL, '. 'csubject VARCHAR(30) NOT NULL, '. 'constraint pk PRIMARY KEY (cid) )' ; $result = mysql_query($query, $link); if(!$result) {die( 'Error in SQL: ' . mysql_error());} mysql_close($link); ?>
  • 18. Example ex2 <?php echo &quot;Welcome to Vrbsky's DB&quot;; // Connect to MySQL $link = mysql_connect(&quot;localhost&quot;, &quot;vrbsky&quot;, “password&quot;); if (!$link) {die('Not connected: '. mysql_error()); } // see if connected // Select DB will use mysql_select_db('vrbsky') or die ('Could not select database'); // see if worked // Now the query $query = &quot;Select * from testit&quot;; // 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 &quot;<hr>&quot;; //horizontal line echo &quot;id: &quot;. $row[&quot;id&quot;] . &quot;<br />&quot;; echo &quot;age: &quot; . $row[&quot;age&quot;] . &quot;<br />&quot;; } mysql_free_result ($result); mysql_close($link); // disconnecting from MySQL ?>
  • 20. Accessing result rows <?php $link=mysql_connect (&quot;localhost&quot;, &quot;vrbsky&quot;, “password&quot;); mysql_select_db('vrbsky') or die('Cannot select database'); $query = &quot;SELECT ssn, lname FROM employee&quot;; $result = mysql_query($query, $link); //Using column name while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo &quot;SSN :{$row['ssn']} <br>&quot; . &quot;Last : {$row['lname']} <br> <br>&quot;; } // Using an index // while($row = mysql_fetch_array($result, MYSQL_NUM)) // { // echo &quot;SSN :{$row[0]} <br>&quot; . //  &quot;Last : {$row[1]} <br><br>&quot;; // } mysql_close($link); ?>
  • 21. Forms and input Can use HTML to create forms Users can input values to use as host variables in calls to mysql
  • 22. HTML code The following code uses a form to ask for input values to a table It will execute a php file after values are input in the form To use those values in php file, must use $_POST[‘var_name’]
  • 23. $_POST function < form method=&quot;post&quot; action=&quot;example.php&quot;> variables from a form will be placed into an array $_POST Index into array is form data name Info sent from form invisible With POST no limits on the amount of info to send Different from $_GET function where Info sent is displayed in browser’s address bar Max 100 characters
  • 24. HTML and PHP and MYSQL ex3.html <html> <head> </head> <center> <!-- The following line results in php code executed after input values in form -> <form method=&quot;post&quot; action=&quot;example3.php&quot;> <table> <tr><td align=&quot;left&quot;>ID</td> <td><input type=&quot;text&quot; name=&quot;id&quot;></td> </tr> <tr><td align=&quot;left&quot;>Age</td> <td><input type=&quot;text&quot; name=&quot;age&quot; size=&quot;15&quot;></td> </tr> <tr><colspan=&quot;2&quot;> <p align=&quot;center&quot;> <input type=&quot;submit&quot; value=&quot;Enter record&quot;> </td> </tr> </table> </form> </center> </html>
  • 25. PHP code PHP code places values input from form into local variables Connects to database Inserts values into tables Prints out values
  • 26. example3.php <?php // This is example3.php used in previous .htm code $link = mysql_connect(&quot;localhost&quot;, &quot;svrbsky&quot;, “cwid&quot;); if (!$link) {die('Not connected: '. mysql_error()); } mysql_select_db('vrbsky') or die ('Could not select database'); $id= $_POST['id']; $age = $_POST['age']; $query = &quot;insert into testit values ('$id', '$age')&quot;; $result = mysql_query($query); if (!$result) {die('SQL error: ' . mysql_error());} mysql_close($link); print &quot;<html><body><center>&quot;; print &quot;<p>You have just entered this record<p>&quot;; print &quot;ID: $id<br>&quot;; print &quot;Age: $age&quot;; print &quot;</body></html>&quot;; ?>
  • 28. Example HTML and PHP ex4.html <html> <body> <center> <form method=&quot;post&quot; action=&quot;example4.php&quot;> <!-- places values in associative array called $_POST --> <font size=&quot;18&quot;>Complete the Select Statement</font><br> Select <input type=&quot;text&quot; name=&quot;select&quot; size=&quot;60&quot; value=&quot; ;&quot; ><br> <input type=&quot;hidden&quot; name=&quot;_query_form2&quot; value=&quot;1&quot;> <input type=&quot;submit&quot; nvalue=&quot;Get Query&quot;></form> <table border=&quot;1&quot;> </table></center></body></html>
  • 29. example4.php code segment <?php //This is example4.php referenced in previous .html code $link = mysql_connect(&quot;localhost&quot;, &quot;svrbsky&quot;, “cwid&quot;); if(!$link) { die('Not connected: '.mysql_error);} mysql_select_db('vrbsky'); // isset tests if the value of the variable is set if(isset($_POST['_query_form2']) && isset($_POST['select'])) { $select = 'select'.$_POST['select']; $result = mysql_query($select, $link); if(!$result) { echo mysql_error(); } else { while($row = mysql_fetch_array($result, MYSQL_NUM)) { echo &quot;<hr>&quot;; // horizontal line echo &quot;<tr>&quot;; for($count = 0; $count < 10; $count++) { if(isset($row[$count])) echo &quot; <td>{$row[$count]}</td>&quot;; if(!isset($row[$count]) && isset($row[++$count])) { echo &quot;<td></td>&quot;; $count--; } } echo &quot;</tr>&quot;; } } } ?>
  • 31. Our Setup This this link to our machine: Vrbsky-linux-1.cs.ua.edu 130.160.68.71
  • 32. Our setup A machine for us to use PHP and MySQL address of machine is: Vrbsky-linux-1.cs.ua.edu or 130.160.68.71 This is a linux machine Emacs, vi (I haven’t used this since the ’80s) username is 1 st name initial followed by last name with a password of CWID Ex. John Doe username is: jdoe You need to use SSH Secure Shell to directly Quick Connect to this machine
  • 33. Our setup Use vi (or whatever) to create new PHP and HTML files OR you can just edit files locally then use SSH file transfer to this machine
  • 34. Our Setup To run MySQL directly To start up MySQL type in: mysql –u your_login –p It will then prompt you for your password You must create a db created with the same name as your login using: create database your_login The next time you start up MySQL type in: mysql –u your_login –D your_login –p where –D is you database
  • 35. Our setup To use MySQL through PHP Create/save a .php file using an editor Make sure the file is on the lamp.cs.ua.edu machine in the root directory Sample program: <?php Echo “Hello World”; ?> To run it, from IE, type in: ip address/ yourlogin /filename 130.160.47.52/vrbsky/Hello.php or lamp.cs.ua.edu/vrbsky/Hello.php
  • 36. Won’t this be fun for an assignment? Lots of great links on the web to get into Disadvantage: How to determine what is error?