Вы находитесь на странице: 1из 134

PHP & MySQL

Corporate Training Material


Design & Created by Karma E Shop

What is PHP UsedFor?

PHP is a general-purpose server-side


scripting language originally designed for
web development
to
produce
dynamic web pages
PHP can interact with MySQL databases

What is PHP?

PHP == Hypertext Preprocessor


Open-source, server-side scripting language
Used to generate dynamic web-pages
PHP scripts reside between reserved PHP tags
This allows the programmer to embed PHP
scripts within HTML pages

What is PHP (contd)

Interpreted language, scripts are parsed at runtime rather than compiled beforehand
Executed on the server-side
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

What does PHP code look like?

Structurally similar to C/C++


Supports procedural and object-oriented
paradigm (to some degree)
All PHP statements end with a semi-colon
Each PHP script must be enclosed in the
reserved PHP tag
<?php

?>

Comments in PHP

Standard C, C++, and shell comment


symbols
// C++ and Java-style comment
# Shell-style comments
/* C-style comments
These can span multiple lines */

Another version is this one, which is the


same kind of tags used for e.g. blocks of
JavaScript code:
<script language="php"> [code
here] </script>

Those two options are always available. However, a lot


of PHP installations are set up to allow the short version
as well:
<? [code here] ?>
On some servers, ASP style tags have been enabled.
They look like this:
<% [code here] %>

Since this is not necessarily supported on all


servers, you may wish to use the full version
instead.
The same goes for the special output version,
which looks like this:
<?= [output here] ?>

Variables in PHP

PHP variables must begin with a $ sign


Case-sensitive ($Foo != $foo != $fOo)
Global and locally-scoped variables

Global variables can be used anywhere


Local variables restricted to a function or class

Certain variable names reserved by PHP

Form variables ($_POST, $_GET)


Server variables ($_SERVER)
Etc.

Variable usage
<?php
$foo = 25;
$bar = Hello;
$foo = ($foo * 7);
$bar = ($bar * 7);
?>

// Numerical variable
// String variable
// Multiplies foo by 7
// Invalid expression

<?php $myVar = 42; echo $myVar; ?>

In and out of PHP

<?php $myVar = "Hello world!"; echo "<b>" .


$myVar . "</b>"; ?>

<?php $myVar = "Hello world!"; ?> <i>We


have HTML <u>all</u> over the place here!
</i><br /> <i>But some PHP as well, as you
can see:</i><br /> A message from PHP:
<b><?php echo $myVar; ?></b>

Echo

The PHP command echo is used to output the


parameters passed to it

The typical usage for this is to send data to the


clients web-browser

Syntax

void echo (string arg1 [, string argn...])


In practice, arguments are not passed in parentheses
since echo is a language construct rather than an
actual function

Echo example
<?php
$foo = 25;
$bar = Hello;
echo
echo
echo
echo
echo
?>

$bar;
$foo,$bar;
5x5=,$foo;
5x5=$foo;
5x5=$foo;

// Numerical variable
// String variable
//
//
//
//
//

Outputs
Outputs
Outputs
Outputs
Outputs

Hello
25Hello
5x5=25
5x5=25
5x5=$foo

Notice how echo 5x5=$foo outputs $foo rather than replacing it with 25
Strings in single quotes ( ) are not interpreted or evaluated by PHP
This is true for both variables and character escape-sequences (such as
\n or \\)

Arithmetic Operations
<?php
$a=15;
$b=30;
$total=$a+$b;
Print $total;
Print <p><h1>$total</h1>;
// total is 45
?>

$a - $b
$a * $b
$a / $b
$a += 5

// subtraction
// multiplication
// division
// $a = $a+5 Also works for *= and /=

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


Control Structures: Are the structures within a language
that allow us to control the flow of execution through a
program or script.
Grouped into conditional (branching) structures (e.g.
if/else) and repetition structures (e.g. while loops).
Example if/else if/else statement:
if ($foo == 0) {
echo The variable foo is equal to 0;
}
else if (($foo > 0) && ($foo <= 5)) {
echo The variable foo is between 1 and 5;
}
else {
echo The variable foo is equal to .$foo;
}

If ... Else...

If (condition)
<?php
If($user==John)
{
{
Print Hello John.;
Statements; }
Else
}
{
Print You are not John.;
Else
}
?>
{
Statement;
No THEN in PHP
}

<?php

$number = 42;
if($number == 42)
echo "The number is 42!";
?>

<?php
$animal = "Cat";
if($animal == "Dog")
echo "It's a dog!";
else
echo "I'm sure it's some sort of animal, but
not a dog!"
?>

While Loops

While (condition)
{
Statements;
}

<?php
$count=0;
While($count<3)
{
Print hello PHP. ;
$count += 1;
// $count = $count + 1;
// or
// $count++;
?>

hello PHP. hello PHP. hello PHP.

The while loop

<?php $i = 0; while($i < 5) { echo $i."<br>";


$i++; } ?>

The do-while loop

<?php $i = 0; do { echo $i."<br>"; $i++; }


while($i < 0); ?>

The for loop

<?php for($i = 0; $i < 5; $i++) { echo


$i."<br />"; } ?>

The foreach loop

<?php $animals = array("Dog", "Cat",


"Snake", "Tiger"); foreach($animals as
$animal) echo $animal . "<br />"; ?>

The for loop

<?php $animals = array(1 => "Dog", "Cat",


"Snake", "Tiger"); foreach($animals as $key
=> $value) echo "Animal number " . $key . "
is a " . $value . "<br />"; ?>

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 NOSHADE WIDTH=100%>
<i>Copyright 2008-2010 KSU </i></font><br>
<i>ALL RIGHTS RESERVED</i></font><br>
<i>URL: http://www.kent.edu</i></font><br>

Including files

One of the most popular features of PHP is the ability to include files. This
allows you to separate your code into multiple files, and re-use them in

.
<i>Below this, content will come from another
file!</i> <br /><br /><br /> <?php $number1
= 20; include("includedfile.php"); ?> <br /><br
/><br /> <i>We're back, after the included file
has ended!</i>
various places

Including files

<b>This text is included!</b><br />


<?php $number2 = 30;
echo "And so is this PHP code - ".$number1."
+ ".$number2." equals " . ($number1 +
$number2) . "!"; ?>

Working with strings

<?php $string = "Hello world!"; $startPos =


strpos($string, "world"); $length =
strlen("world"); $substring = substr($string,
$startPos, $length); echo "A specific part of
the string: " . $substring; ?>

Working with arrays

<?php $animals = array("Monkey", "Lion",


"Turtle", "Horse"); echo $animals[2]; ?>

$namesAndAges = array("John Doe" => 45,


"Jane Doe" => 33, "Dog Doe" => 11); echo
"The age of Jane Doe: " .
$namesAndAges["Jane Doe"]; ?>

Multidimensional arrays

<?php $contacts = array(); $contacts["Friends"]


= array("Me", "John Doe"); $contacts["Family"] =
array("Mom", "Dad"); $contacts["Enemies"] =
array("Stalin", "Hitler"); foreach($contacts as
$categoryName => $value) { echo "<b>" .
$categoryName . ":</b><br />";
foreach($contacts[$categoryName] as $name)
{ echo $name . "<br />"; } echo "<br />"; } ?>

Implode and explode

<?php $values = "Rabbit|Whale|Penguin|


Bird"; $array = explode("|", $values);
print_r($array); echo "<br /><br />"; $string =
implode(" and ", $array); echo $string; ?>

Is a value in the array?

<?php $animals = array("Dog", "Tiger",


"Snake", "Goat"); if(in_array("Snake",
$animals)) echo "Snake is in the array!"; else
echo "No snake in the array!"; ?>

Sorting arrays

<?php $animals = array("Dog", "Tiger", "Snake", "Goat",


"Rabbit", "Whale", "Bird"); echo "Unsorted animals: " .
implode(", ", $animals); echo "<br /><br />";
sort($animals); echo "Sorted animals: " . implode(", ",
$animals); echo "<br /><br />"; $animals =
array_reverse($animals); echo "Sorted animals,
descending order: " . implode(", ", $animals); ?>

Date Display
2009/4/1

Wednesday, April 1, 2009

$datedisplay=date(yyyy/m/d);
Print $datedisplay;
# If the date is April 1st, 2009
# It would display as 2009/4/1

$datedisplay=date(l, F m, Y);
Print $datedisplay;
# If the date is April 1st, 2009
# Wednesday, April 1, 2009

<?php $number = 10; if($number > 20) echo


"Number is bigger than 20!"; elseif($number
> 10) echo "Number is bigger than 10!"; else
echo "The number seems a bit low..." ?>

The ternary operator

<?php $numberOfItems = 2; $output =


"There is "; if($numberOfItems > 0) $output .=
"something"; else $output .= "nothing";
$output .= " in your basket"; echo $output; ?>

<?php $numberOfItems = 0; $output =


"There is " . (($numberOfItems > 0) ?
"something" : "nothing") . " in your basket";
echo $output; ?>

The switch statement

<?php $answer = 0; if(isset($_GET["answer"])) $answer


= $_GET["answer"]; switch($answer) { default: echo
"Which version of PHP are you using?<br /><br />"; echo
"<a href=\"?answer=3\">3</a><br />"; echo "<a href=\"?
answer=4\">4</a><br />"; echo "<a href=\"?
answer=5\">5</a><br />"; break; case 3: echo "Ugh
that's old, upgrade now!"; break; case 4: echo "Still on
version 4? Give PHP 5 a try!"; break; case 5: echo
"Good choice!"; break; } ?>

$color = "red"; switch($color) { case "red":


case "blue": case "green": echo "Nice basic
color!"; break; case "black": echo "Too dark!";
break; case "white": echo "Too bright!"; break;
}

Month, Day & Date Format


Symbols
M
F
m
n
Day of Month
Day of Month
Day of Week
Day of Week

Jan
January
01
1
d
J
l
D

01
1
Monday
Mon

Functions

Functions MUST be defined before then can be


called
Function headers are of the format
function functionName($arg_1, $arg_2, , $arg_n)

Note that no return type is specified

Unlike variables, function names are not case


sensitive (foo() == Foo() == FoO())

Functions example
<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
return $arg_2;
}
$result_1 = foo(12, 3);
echo $result_1;
echo foo(12, 3);
?>

// Store the function


// Outputs 36
// Outputs 36

<?php function SayHello($to) { echo "Hello,


".$to; } SayHello("World"); ?>

<?php function GreetCoder($name, $msg =


"Hello, coder!") { echo "A message to " .
$name . ": " . $msg; } GreetCoder("John
Doe"); echo "<br /><br />"; GreetCoder("John
Doe", "This is a custom message!"); ?>

Data types

PHP consists of 4 basic data types:


boolean - a boolean is actually much like an integer, but with only
two possible values: 0 or 1, which is either false or true.
integer - a number with no decimals, e.g 3 or 42.
float (sometimes referred to as double) - a number that may
include decimals, e.g. 42.3 or 10.9.
string - A number of characters, which combined makes a text
string.

Working with numbers

<?php $number1 = 6; $number2 = 2; echo


"Addition: " . ($number1 + $number2); echo
"<br /><br />"; echo "Substraction: " .
($number1 - $number2); echo "<br /><br />";
echo "Multiplication: " . ($number1 *
$number2); echo "<br /><br />"; echo
"Division: " . ($number1 / $number2); echo
"<br /><br />"; ?>

<?php $number1 = "10"; $number2 = 20;


if((is_numeric($number1)) &&
(is_numeric($number2))) echo "Result: " .
($number1 + $number2); else echo "Both
variables have to be numbers!"; ?>

Need to Know the terms

Class :A collection of interrelated functions


and variables that manipulates in single idea
or concept.
Instantiate: To Allocate memory for a class
Object : An instance of the class
Method :A function within class
Class member:A method or variable with in a
class

Defining and using a class

To create a class, you need to use the keyword class followed by the name
of the class. The name of the class should be meaningful to exist within the
system (See note on naming a class towards the end of the article). The
body of the class is placed between two curly brackets within which you
declare class data members/variables and class methods.

<?php
class User
{ } ?>

Class structure
class <class-name>
{ <class body :- Data Members &amp;
Methods>; }

class User {
public $name;
public $age;
public function Describe()
{ return $this->name . " is " . $this->age . "
years old"; }
}
$user = new User(); $user->name = "John Doe"; $user->age = 42;
echo $user->Describe();

class Customer { private $first_name,


$last_name; public function
setData($first_name, $last_name) { $this>first_name = $first_name; $this->last_name
= $last_name; } public function printData()
{ echo $this->first_name . " : " . $this>last_name; } }

Public

Anyone can access to method and property


default

Public Example
<?php
Class person{
Public function getName()
{
return Mahandra;
}
}
?>
<?php
$p = new person ();
echo $p->getName();
?>

?>

Private

Only the class itself can access to method


and property.

<?php
Class person{
Public function firstName()
{
return Mahandra;
}
Privite function LastName()
{
ReturnJames;
}
}
?>
<?php
$p = new person ();
echo $p->firstName();
echo $p->LastName();
?>

Protected

Only the class and class extended can have


access to method and property

Constructors and
destructors

A constructor and a destructor are special


functions which are automatically called when
an object is created and destroyed.

construct

functions with two underscore characters


before the name usually tells you that it's a
so-called magic function, a function with a
specific purpose and extra functionality, in
comparison to normal functions. So, a
function with the exact name "__construct", is
the constructor function of the class and will
be called automatically when the object is
created

<?php class Animal { public $name = "Noname animal"; public function


__construct($name) { $this->name =
$name; } } $animal = new Animal("Bob the
Dog"); echo $animal->name; ?>

Destructors

A destructor is called when the object is


destroyed. In some programming languages,
you have to manually dispose of objects you
created, but in PHP, it's handled by the
Garbage Collector, which keeps an eye on
your objects and automatically destroys them
when they are no longer needed.

Destructors

<?php class Animal { public $name = "Noname animal"; public function


__construct($name) { echo "I'm alive!"; $this>name = $name; } public function
__destruct() { echo "I'm dead now :("; } }
$animal = new Animal("Bob"); echo "Name of
the animal: " . $animal->name; ?>

Visibility

Visibility is a big part of OOP. It allows you to


control where your class members can be
accessed from, for instance to prevent a
certain variable to be modified from outside the
class. The default visibility is public, which
means that the class members can be
accessed from anywhere. This means that
declaring the visibility is optional, since it will
just fall back to public if there is no access
modifier

Visibility

PHP is pretty simple in this area, because it


comes with only 3 different access modifiers:
private, protected and public.
Private members can only be accessed from inside the class itself.
Protected members can only be accessed from inside the class it
self and its child classes.
Public members can be accessed from anywhere - outside the
class, inside the class it self and from child classes.

Inheritance

Inheritance is one of the most important


aspects of OOP. It allows a class to inherit
members from another class.

class Animal {
public $name;
public function Greet()
{ return "Hello, I'm some sort of animal and my name is " . $this->name;
}
}
class Dog extends Animal {
public function Greet()
{ return "Hello, I'm a dog and my name is " . $this->name; }
}
$animal = new Animal(); echo $animal->Greet(); $animal = new Dog();
$animal->name = "Bob"; echo $animal->Greet();

Abstract classes

Abstract classes are special because they


can never be instantiated. Instead, you
typically inherit a set of base functionality
from them in a new class

abstract class Animal { public $name; public $age; public function


Describe() { return $this->name . ", " . $this->age . " years old"; }
abstract public function Greet(); }
class Dog extends Animal { public function Greet() { return "Woof!"; }
public function Describe() { return parent::Describe() . ", and I'm a
dog!"; } }
$animal = new Dog(); $animal->name = "Bob"; $animal->age = 7;
echo $animal->Describe(); echo $animal->Greet();

Static classes

Since a class can be instantiated more than once, it means that the
values it holds, are unique to the instance/object and not the class
itself. This also means that you can't use methods or variables on a
class without instantiating it first, but there is an exception to this
rule. Both variables and methods on a class can be declared as
static (also referred to as "shared" in some programming
languages), which means that they can be used without instantiating
the class first. Since this means that a class variable can be
accessed without a specific instance, it also means that there will
only be one version of this variable. Another consequence is that a
static method cannot access non-static variables and methods,
since these require an instance of the class.

<?php class User { public $name; public $age; public


static $minimumPasswordLength = 6; public function
Describe() { return $this->name . " is " . $this->age . "
years old"; } public static function
ValidatePassword($password) { if(strlen($password) >=
self::$minimumPasswordLength) return true; else return
false; } } $password = "test";
if(User::ValidatePassword($password)) echo "Password
is valid!"; else echo "Password is NOT valid!"; ?>

Class constants

When you declare a constant, you assign a


value to it, and after that, the value will never
change.

<?php class User { const DefaultUsername =


"John Doe"; const MinimumPasswordLength
= 6; } echo "The default username is " .
User::DefaultUsername; echo "The minimum
password length is " .
User::MinimumPasswordLength; ?>

The "final" keyword

You may want to prevent a class from being


inherited from or a function to be overridden.
This can be done with the final keyword,
which simply causes PHP to throw an error if
anyone tries to extend your final class or
override your final function.

A final class could look like this:

final class Animal { public $name; }

A class with a final function could look like


this:

class Animal { final public function Greet()


{ return "The final word!"; } }

Overloading

Overloading in PHP provides means to dynamically


"create" properties and methods. These dynamic entities
are processed via magic methods one can establish in a
class for various action types.
The overloading methods are invoked when interacting
with properties or methods that have not been declared
or are not visible in the current scope. The rest of this
section will use the terms "inaccessible properties" and
"inaccessible methods" to refer to this combination of
declaration and visibility.
All overloading methods must be defined as public.

Image.php

<?php
class Image {

function __construct() {
echo 'Class Image loaded successfully <br />';
}

}
?>

Test.php

<?php
class Test {

function __construct() {
echo 'Class Test working <br />';
}

}
?>

Index.php

<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}

$a = new Test();
$b = new Image();
?>

throw exception

<?php
function __autoload($class_name) {
if(file_exists($class_name . '.php')) {
require_once($class_name . '.php');
} else {
throw new Exception("Unable to load $class_name.");
}
}

try {
$a = new Test();
$b = new Image();
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
?>

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>

http://www.cs.kent.edu/~nruan/form.php

WHY
PHP

Sessions
?
Whenever you want to create a website that allows you to store

and display information about a user, determine which user groups


a person belongs to, utilize permissions on your website or you just
want to do something cool on your site, PHP's Sessions are vital to
each of these features.
Cookies are about 30% unreliable right now and it's getting worse
every day. More and more web browsers are starting to come with
security and privacy settings and people browsing the net these
days are starting to frown upon Cookies because they store
information on their local computer that they do not want stored
there.
PHP has a great set of functions that can achieve the same results
of Cookies and more without storing information on the user's
computer. PHP Sessions store the information on the web server in
a location that you chose in special files. These files are connected
to the user's web browser via the server and a special ID called a
"Session ID". This is nearly 99% flawless in operation and it is

PHP - Sessions
Sessions store their identifier in a cookie in the clients browser
Every page that uses session data must be proceeded by the
session_start() function
Session variables are then set and retrieved by accessing the
global $_SESSION[]
Save it as session.php
<?php
session_start();
if (!$_SESSION["count"])
$_SESSION["count"] = 0;
if ($_GET["count"] == "yes")
$_SESSION["count"] = $_SESSION["count"] + 1;
echo "<h1>".$_SESSION["count"]."</h1>";
?>
<a href="session.php?count=yes">Click here to count</a>

http://www.cs.kent.edu/~nruan/session.php

Avoid Error PHP - Sessions


PHP Example: <?php
echo "Look at this nasty error below:<br />";
session_start();
?>

Error!
Warning: Cannot send session cookie - headers already
sent by (output started at
session_header_error/session_error.php:2) in
session_header_error/session_error.php on line 3
Warning: Cannot send session cache limiter - headers
already sent (output started at
session_header_error/session_error.php:2) in
session_header_error/session_error.php on line 3

PHP Example: <?php


session_start();
echo "Look at this nasty error below:";
?>
Correct

Destroy PHP - Sessions


Destroying a Session
why it is necessary to destroy a session when the session will get
destroyed when the user closes their browser. Well, imagine that
you had a session registered called "access_granted" and you
were using that to determine if the user was logged into your site
based upon a username and password. Anytime you have a login
feature, to make the users feel better, you should have a logout
feature as well. That's where this cool function called
session_destroy() comes in handy. session_destroy() will
completely demolish your session (no, the computer won't blow
up or self destruct) but it just deletes the session files and clears
any trace of that session.
NOTE: If you are using the $_SESSION superglobal array, you must
clear the array values first, then run session_destroy.
Here's how we use session_destroy():

Destroy PHP - Sessions


<?php
// start the session
session_start();
header("Cache-control: private"); //IE 6 Fix
$_SESSION = array();
session_destroy();
echo "<strong>Step 5 - Destroy This Session
</strong><br />";
if($_SESSION['name']){
echo "The session is still active";
} else {
echo "Ok, the session is no longer active! <br />";
echo "<a href=\"page1.php\"><< Go Back Step
1</a>";
}
?>

PHP Overview

Easy learning
Syntax Perl- and C-like syntax. Relatively
easy to learn.
Large function library
Embedded directly into HTML
Interpreted, no need to compile
Open Source server-side scripting language
designed specifically for the web.

PHP Overview (cont.)

Conceived in 1994, now used on +10 million web


sites.
Outputs not only HTML but can output XML,
images (JPG & PNG), PDF files and even Flash
movies all generated on the fly. Can write these
files to the file system.
Supports a wide-range of databases (20+ODBC).
PHP also has support for talking to other services
using protocols such as LDAP, IMAP, SNMP,
NNTP, POP3, HTTP.

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>

http://www.cs.kent.edu/~nruan/sample.php

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()
include()
mysql_query()
mysql_fetch_array()

mysql_select_db()
mysql_num_rows()
mysql_close()

History of PHP

PHP began in 1995 when Rasmus Lerdorf developed a


Perl/CGI script toolset he called the Personal Home
Page or PHP
PHP 2 released 1997 (PHP now stands for Hypertex
Processor). Lerdorf developed it further, using C instead
PHP3 released in 1998 (50,000 users)
PHP4 released in 2000 (3.6 million domains).
Considered debut of functional language and including
Perl parsing, with other major features
PHP5.0.0 released July 13, 2004 (113 libraries>1,000
functions with extensive object-oriented programming)
PHP5.0.5 released Sept. 6, 2005 for maintenance and
bug fixes

Recommended Texts for


Learning PHP

Larry Ullmans books from the Visual Quickpro


series
PHP & MySQL for Dummies
Beginning PHP 5 and MySQL: From Novice to
Professional by W. Jason Gilmore

(This is more advanced and dense than the others,


but great to read once youve finished the easier
books. One of the best definition/description of
object oriented programming Ive read)

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/chatroo
m.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

Вам также может понравиться