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

36
PHP and MySQL

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

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

PHP and MySQL

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

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

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

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

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

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.

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

PHP - specifics

• Delimiters: <?php ?> or just <? ?>• PHP parses code within delimiters• Code outside delimiter sent to output, not parsed• Block comments /* */ • Inline comments // #

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

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.)

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

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

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

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)

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

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

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

Easy Database Integration

• For example:

MySQL

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

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!

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

• You can connect to MySQL directly

• OR

• You can connect to MySQL through .php

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

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

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

MySQL commands

mysql> LOAD DATA LOCAL INFILE “file_name” INTO TABLE table_name;

mysql> file_name (containing a query)

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

• You can connect to MySQL directly

• OR

• You can connect to MySQL through .php

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

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)

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

PHP and MySQL – ex1<?php

$link=mysql_connect ("localhost", "vrbsky", “password");

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);

?>

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

Example ex2<?php

echo "Welcome to Vrbsky's DB";

// Connect to MySQL$link = mysql_connect("localhost", "vrbsky", “password");if (!$link) {die('Not connected: '. mysql_error()); } // see if connected// Select DB will usemysql_select_db('vrbsky') 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 cursorwhile ($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?>

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

http://vrbsky-linux-1.cs.ua.edu/svrbsky/ex1.php

http://vrbsky-linux-1.cs.ua.edu/svrbsky/ex2.php

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

Accessing result rows

<?php$link=mysql_connect ("localhost", "vrbsky", “password");mysql_select_db('vrbsky') or die('Cannot select database'); $query = "SELECT ssn, lname FROM employee";$result = mysql_query($query, $link); //Using column name while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "SSN :{$row['ssn']} <br>" . "Last : {$row['lname']} <br> <br>"; } // Using an index // while($row = mysql_fetch_array($result, MYSQL_NUM)) // { // echo "SSN :{$row[0]} <br>" . //  "Last : {$row[1]} <br><br>"; // }mysql_close($link);?>

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

Forms and input

• Can use HTML to create forms

• Users can input values to use as host variables in calls to mysql

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

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’]

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

$_POST function

<form method="post" action="example.php">

• 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

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

HTML and PHP and MYSQLex3.html

<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">ID</td>

<td><input type="text" name="id"></td>

</tr>

<tr><td align="left">Age</td>

<td><input type="text" name="age" size="15"></td>

</tr>

<tr><colspan="2">

<p align="center">

<input type="submit" value="Enter record">

</td>

</tr>

</table>

</form>

</center>

</html>

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

PHP code

• PHP code places values input from form into local variables

• Connects to database

• Inserts values into tables

• Prints out values

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

example3.php<?php

// This is example3.php used in previous .htm code

$link = mysql_connect("localhost", "svrbsky", “cwid");

if (!$link) {die('Not connected: '. mysql_error()); }

mysql_select_db('vrbsky') or die ('Could not select database');

$id= $_POST['id'];

$age = $_POST['age'];

$query = "insert into testit values ('$id', '$age')";

$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 "ID: $id<br>";

print "Age: $age";

print "</body></html>";

?>

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

• http://vrbsky-linux-1.cs.ua.edu/svrbsky/ex3.html

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

Example HTML and PHPex4.html

<html><body><center> <form method="post" action="example4.php"> <!-- places values in associative array called $_POST --> <font size="18">Complete the Select Statement</font><br> Select <input type="text" name="select" size="60" value=" ;" ><br> <input type="hidden" name="_query_form2" value="1"> <input type="submit" nvalue="Get Query"></form><table border="1"></table></center></body></html>

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

example4.php code segment<?php //This is example4.php referenced in previous .html code $link = mysql_connect("localhost", "svrbsky", “cwid"); 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 "<hr>"; // horizontal line echo "<tr>"; for($count = 0; $count < 10; $count++) { if(isset($row[$count])) echo " <td>{$row[$count]}</td>"; if(!isset($row[$count]) && isset($row[++$count])) { echo "<td></td>"; $count--; } }

echo "</tr>"; } } }?>

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

• http://vrbsky-linux-1.cs.ua.edu/svrbsky/ex4.html

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

Our Setup

• This this link to our machine:– Vrbsky-linux-1.cs.ua.edu – 130.160.68.71

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

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 1st 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

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

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

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

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

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

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

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

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