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

  • 33,391 views
Uploaded on

 

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
33,391
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
126
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. PHP and MySQL
  • 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
    • ?>
  • 19.
    • http://vrbsky-linux-1.cs.ua.edu/svrbsky/ex1.php
    • http://vrbsky-linux-1.cs.ua.edu/svrbsky/ex2.php
  • 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;;
    • ?>
  • 27.
    • http://vrbsky-linux-1.cs.ua.edu/svrbsky/ex3.html
  • 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;;
    • }
    • }
    • }
    • ?>
  • 30.
    • http://vrbsky-linux-1.cs.ua.edu/svrbsky/ex4.html
  • 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?