Sei sulla pagina 1di 32

Unit IV:

PHP & MySQL


What is PHP ?
Stands for Hypertext Preprocessor
General-purpose, server-side(executed on the server-side)
scripting language used to design dynamic, interactive
Web sites.
dynamic: a page whose contents can change automatically
each time the page is viewed
interactive: a site that responds to input from its visitors
Free, open source
PHP can interact with MySQL databases
Purpose: to process information and produce
hypertext (HTML) as a result.
What is PHP?
-- PHP scripts can be embedded within HTML pages
-- an interpreted language PHP script is processed by
the PHP engine each time its run
-- process of running a PHP script on a Web server
1. A visitor requests a Web page by clicking a link, or typing
the pages URL. The visitor can also send data to the Web
server either using a form or via AJAX (Asynchronous
JavaScript And XML).
2. Web server recognizes that the requested URL is a PHP
script, and instructs the PHP engine to process and run
the script.
3. The script runs, and when its finished it usually sends an
HTML page to the Web browser
What is PHP (contd)
Interpreted language, scripts are parsed at run-time rather
than compiled beforehand
Source-code not visible by client
View Source in browsers does not display the PHP code
Various built-in functions allow for fast development
Compatible with many popular databases
PHP files can contain text, HTML, CSS, JavaScript, and
PHP code
PHP files have extension ".php"
What Can PHP Do?
-- generate dynamic page content
-- create, open, read, write, delete, and close files on the server
-- collect form data
-- send and receive cookies
-- add, delete, modify data in your database
-- used to control user-access
-- encrypt data
PHP not only output HTML but also images, PDF files, and
even Flash movies.
Why PHP?
-- Platform flexibility : runs on various platforms
-- Server compatibility: compatible with almost all servers used
today (Apache, IIS)
-- Integrated database support: It has built-in support for the
most popular databases like MySQL, that means it is easy to start
using databases, no additional drivers needs to be installed, just to
use the mysql-functions.
-- free (www.php.net)
-- Easy to use: PHP doesn't need to be compiled, so it's just to
write the script and then upload it to the server and then update the
browser.
-- cheap and easy to setup and create a website using PHP
-- Fast Load Time PHP results in faster site loading speeds. PHP
codes runs much faster.
Why PHP?

-- Cheap hosting: Since PHP has existed for long time and works
good on both Linux and Windows, and many webservers have
support for it. There is no problem to find hosting with PHP pre-
installed. It is available through a hosting provider at no additional
cost.
-- Less Expensive Software In working with PHP, most tools
associated with the program are open source software, such as
WordPress, so you need not pay for them.
PHP code syntax
Structurally similar to C/C++
A PHP script can be placed anywhere in the document
Supports procedural and OO pattern
All PHP statements end with a semi-colon
Each PHP script must be enclosed in the reserved PHP
tag
Example
<?php
<?php
echo "Hello World!";
?>
?>
Echo (print)
echo is used to output the parameters passed to it
Syntax: echo (string arg1 [, string arg n...])
arguments are not passed in () since echo is a language
construct rather than an actual function
<?php
$n = 25; // Numerical variable
$bar = Hello; // String variable

echo $bar; // Outputs Hello


echo $n,$bar; // Outputs 25Hello
echo 5x5=,$n; // Outputs 5x5=25
echo 5x5=$n; // Outputs 5x5=25
echo 5x5=$n; // Outputs 5x5=$n
?>
Strings in single quotes ( ) are not interpreted or evaluated by
PHP
Comments in PHP
A comment in PHP code is a line that is not read/executed
as part of the program.

// This is a single-line comment

# Shell comment which is also a single-line comment

/*
This is a multiple-lines comment
*/

Note: PHP keywords and user defined functions are not


case sensitive.
Variables in PHP
PHP variables must begin with a $ sign
Case-sensitive ($Foo != $foo != $fOo)

Certain variable names reserved by PHP

Form variables ($_POST, $_GET)


Server variables ($_SERVER)
e.g. $txt = "Hello world!";
$x = 5;
Loosely typed language: no need to specify datatype

PHP Variables Scope


Data types in PHP
A variables data type determines what operations can be carried
out on the data, as well as the amount of memory needed to hold
the data.
Arithmetic Operations
<?php
$a=15;
$b=30;
$total=$a+$b;
Print $total;
Print <p><h1>$total</h1>;
?>

$a - $b // subtraction
$a * $b // multiplication
$a / $b // division
$a += 5 // $a = $a+5
Concatenation

Use a period to join strings into one.


<?php
$string1=Hello;
$string2=PHP;

$string3=$string1. .$string2;

Print $string3;
?>

Hello PHP
Escaping the Character
If the string has a set of double quotation
marks that must remain visible, use the \
[backslash] before the quotation marks to
ignore and display them.

<?php
$heading=\Computer Science\;
Print $heading;
?>

Computer Science
PHP Control Structures
allow us to control the flow of execution of program
Grouped into conditional/branching structures (if/else) and
repetition structures (while loops).

Example:
if ($n == 0)
{
echo The variable n is equal to 0;
}
else if (($n > 0) && ($n <= 5))
{
echo The variable n is between 1 and 5;
}
else {
echo The variable n is equal to .$n;
}
If ... Else...
<?php
If (condition) If($user==John)
{
{ Print Hello John.;
}
Statements; Else
} {
Print You are not John.;
Else }
?>
{
Statement;
}
While Loops
<?php
While (condition) $count=0;
While($count<3)
{ {
Statements; Print hello PHP. ;
$count += 1;
} }
?>

hello PHP. hello PHP. hello PHP.


Functions
Functions MUST be defined before they can be called
Function headers are of the format

function functionName($arg_1, $arg_2, , $arg_n)

Unlike variables, function names are not case sensitive


Functions example
<?php

function foo($arg_1, $arg_2)


{
$arg_2 = $arg_1 * $arg_2;
return $arg_2;
}

$result = foo(12, 3); // Store the function


echo $result; // Outputs 36
echo foo(12, 3); // Outputs 36
?>
Termination
PHP Instruction Termination
-- Each statement made in PHP needs to indicate end of the statement so that
each instruction can be carried out without mix-up.
-- Each statement, or instruction, is terminated with a semicolon.

PHP script termination


-- exit Output a message and terminate the current script
-- void exit ([ string $status ] ) or void exit ( int $status )
-- Terminates execution of the script.
-- exit is a language construct and it can be called without parentheses if no
status is passed.
-- Parameters: status
If status is a string, this function prints the status just before exiting.
If status is an integer, that value will be used as the exit status and not
printed.
Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by
PHP and shall not be used.
The status 0 is used to terminate the program successfully.
e.g. exit("unable to open file);
exit;
Include Files
Include opendb.php;
Include closedb.php;
This inserts files;
The code in files will be inserted into current code.
This will provide useful and protective means once you connect to a
database, as well as for other repeated functions.

Include (footer.php);
The file footer.php might look like:

<hr size=11 width=100%>


<i>Copyright 2008-2010 KSU </i><br>
<i>ALL RIGHTS RESERVED</i><br>
<i>URL: http://www.kent.edu</i><br>
PHP - Forms
Access to the HTTP POST and GET data is simple in PHP
The global variables $_POST[] and $_GET[] contain the
request data
<?php
if ($_POST["submit"])
echo "<h2>You clicked Submit!</h2>";
else if ($_POST["cancel"])
echo "<h2>You clicked Cancel!</h2>";
?>
<form action="form.php" method="post">
<input type="submit" name="submit" value="Submit">
<input type="submit" name="cancel" value="Cancel">
</form>
First PHP script
Save as sample.php:
<! sample.php -->
<html><body>
<strong>Hello World!</strong><br>
<?php
echo <h2>Hello, World</h2>; ?>
<?php
$myvar = "Hello World";
echo $myvar;
?>
</body></html>
Example show data in the tables

Function: list all tables in your database.


Users can select one of tables, and show all
contents in this table.

second.php
showtable.php
second.php
<html><head><title>MySQL Table Viewer</title></head><body>
<?php
// change the value of $dbuser and $dbpass to your username and password
$dbhost = 'hercules.cs.kent.edu:3306';
$dbuser = 'nruan';
$dbpass = *****************;
$dbname = $dbuser;
$table = 'account';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db($dbname))
die("Can't select database");
second.php (cont.)
$result = mysql_query("SHOW TABLES");
if (!$result) {
die("Query to show fields from table failed");
}
$num_row = mysql_num_rows($result);
echo "<h1>Choose one table:<h1>";
echo "<form action=\"showtable.php\" method=\"POST\">";
echo "<select name=\"table\" size=\"1\" Font size=\"+2\">";
for($i=0; $i<$num_row; $i++) {
$tablename=mysql_fetch_row($result);
echo "<option value=\"{$tablename[0]}\" >{$tablename[0]}</option>";
}
echo "</select>";
echo "<div><input type=\"submit\" value=\"submit\"></div>";
echo "</form>";

mysql_free_result($result);
mysql_close($conn);
?>
</body></html>
showtable.php
<html><head>
<title>MySQL Table Viewer</title>
</head>
<body>
<?php
$dbhost = 'hercules.cs.kent.edu:3306';
$dbuser = 'nruan';
$dbpass = **********;
$dbname = 'nruan';
$table = $_POST[table];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
if (!mysql_select_db($dbname))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) die("Query to show fields from table failed!" . mysql_error());
showtable.php (cont.)
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++) {
$field = mysql_fetch_field($result);
echo "<td><b>{$field->name}</b></td>";
}
echo "</tr>\n";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
mysql_close($conn);
?>
</body></html>
Functions Covered
mysql_connect() mysql_select_db()
include()
mysql_query() mysql_num_rows()
mysql_fetch_array() mysql_close()
PHP References
http://www.php.net <-- php home page
http://www.phpbuilder.com/
http://www.devshed.com/
http://www.phpmyadmin.net/
http://www.hotscripts.com/PHP/
http://geocities.com/stuprojects/ChatroomDescription.htm
http://www.academic.marist.edu/~kbhkj/chatroom/chatroom.htm
http://www.aus-etrade.com/Scripts/php.php
http://www.codeproject.com/asp/CDIChatSubmit.asp
http://www.php.net/downloads <-- php download page
http://www.php.net/manual/en/install.windows.php <-- php
installation manual
http://php.resourceindex.com/ <-- PHP resources like sample
programs, text book references, etc.
http://www.daniweb.com/techtalkforums/forum17.html php
forums

Potrebbero piacerti anche