Lecture5 PHP Mysql
Lecture5 PHP Mysql
Lecture5 PHP Mysql
Introduction
Goal
• Not to teach everything about PHP, but provide the basic
knowledge
• Explain code of examples
• Provide some useful references
PHP Basics:
Introduction to PHP
• a PHP file, PHP workings, running PHP.
Basic PHP syntax
• variables, operators, if...else...and switch, while, do while, and
for.
Some useful PHP functions
How to work with
• HTML forms, cookies, files, time and date.
How to create a basic checker for user-entered data
Server-Side Dynamic Web Programming
<?php
…
?>
Comments in PHP
• Standard C, C++, and shell comment symbols
# Shell-style comments
/* C-style comments
These can span multiple lines */
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.
Constants
A constant is an identifier (name) for a simple value. A constant is case-sensitive by
default. By convention, constant identifiers are always uppercase.
<?php
define("__FOO__", "something");
?>
Operators Example Is the same as
• Arithmetic Operators: +, -, *,/ , %, ++, -- x+=y x=x+y
• Assignment Operators: =, +=, -=, *=, /=, %= x-=y x=x-y
x*=y x=x*y
x/=y x=x/y
x%=y x=x%y
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!";
Variable usage
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
<?php
//This is a comment
// for a single-line comment
/* /* and */ for a large
This is
a comment
comment block.
block
*/
?>
</body>
</html>
The server executes the print and echo statements, substitutes output.
Scalars
All variables in PHP start with a $ sign symbol. A variable's type is determined by the
context in which that variable is used (i.e. there is no strong-typing in PHP).
<html><head></head>
<!-- scalars.php -->
<body> <p>
<?php
$foo = true; if ($foo) echo "It is TRUE! <br /> \n";
$txt='1234'; echo "$txt <br /> \n";
Four scalar types:
$a = 1234; echo "$a <br /> \n"; boolean
$a = -123;
echo "$a <br /> \n"; true or false
$a = 1.234;
echo "$a <br /> \n";
integer,
$a = 1.2e3; float,
echo "$a <br /> \n";
$a = 7E-10; floating point numbers
echo "$a <br /> \n";
echo 'Arnold once said: "I\'ll be back"', "<br /> \n";
string
$beer = 'Heineken'; single quoted
echo "$beer's taste is great <br /> \n";
$str = <<<EOD double quoted
Example of string
spanning multiple lines
using “heredoc” syntax.
EOD;
echo $str;
?>
</p>
</body>
</html>
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 client’s
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; // Numerical variable
$bar = “Hello”; // String variable
• 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 // subtraction
• $a * $b // multiplication
• $a / $b // division
• $a += 5 // $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”)
Statements; {
Print “Hello John.”;
} }
Else Else
{
{
Print “You are not John.”;
Statement; }
} ?>
No THEN in PHP
Conditionals: if else
Can execute a set of code depending on a condition
<html><head></head> if (condition)
<!-- if-cond.php -->
<body> code to be executed if condition
is true;
<?php
$d=date("D"); else
echo $d, “<br/>”; code to be executed if condition
if ($d=="Fri")
echo "Have a nice weekend! <br/>";
is false;
else
echo "Have a nice day! <br/>";
date() is a built-in PHP function that
$x=10;
if ($x==10) can be called with many different
{ parameters to return the date
echo "Hello<br />"; (and/or local time) in various formats
echo "Good morning<br />";
}
In this case we get a three letter
?> string for the day of the week.
</body>
</html>
While Loops
• While (condition) <?php
$count=0;
{ While($count<3)
Statements; {
Print “hello PHP. ”;
} $count += 1;
// $count = $count + 1;
// or
// $count++;
?>
<?php <?php
for ($i=1; $i<=5; $i++) $a_array = array(1, 2, 3, 4);
{ foreach ($a_array as $value)
echo "Hello World!<br />"; {
} $value = $value * 2;
?> echo “$value <br/> \n”;
}
?>
loops through a block of code a
<?php
specified number of times $a_array=array("a","b","c");
foreach ($a_array as $key => $value)
{
echo $key." = ".$value."\n";
}
?>
<html><head></head>
<body>
<!–- switch-cond.php -->
<?php
$x = rand(1,5); // random integer switch (expression)
echo “x = $x <br/><br/>”; {
switch ($x) case label1:
{ code to be executed if
case 1: expression = label1;
echo "Number 1"; break;
break; case label2:
case 2: code to be executed if
echo "Number 2"; expression = label2;
break; break;
case 3: default:
echo "Number 3"; code to be executed
break; if expression is different
default: from both label1 and label2;
echo "No number between 1 and 3"; break;
break; }
}
?>
</body>
</html>
Date Display
$datedisplay=date(“yyyy/m/d”);
2012/25/6 Print $datedisplay;
# If the date is June 25th, 2012
# It would display as 2012/25/6
$datedisplay=date(“l, F m, Y”);
Monday, June 25, 2012 Print $datedisplay;
# If the date is June 25th ,2012
# Monday, June 25th,2012
Arrays
An array in PHP is actually an ordered map. A map is a type that maps values to keys.
Day of Month d 01
Day of Month J 1
Day of Week l Monday
Day of Week D Mon
Functions
• Functions MUST be defined before then can be called
• Function headers are of the format
• Note thatfunctionName($arg_1,
function no return type is specified
$arg_2, …, $arg_n)
<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{ Can also define conditional
echo "Example function.\n";
return $retval;
functions, functions within functions,
} and recursive functions.
?>
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
takes_array(array(1,2));
?>
Variable Scope
The scope of a variable is the context within which it is defined.
<?php
$a = 1; /* limited variable scope */
function Test()
{
echo $a; The scope is local within functions,
/* reference to local scope variable */
}
and hence the value of $a is
Test(); undefined in the “echo” statement.
?>
<?php <?php
$a = 1; function Test()
$b = 2; global {
function Sum() static
static $a = 0;
{
global $a, $b;
refers to its echo $a;
does not lose
$a++;
$b = $a + $b; global } its value.
}
Sum();
version. Test1();
Test1();
echo $b; Test1();
?> ?>
Including Files
The include() statement includes and evaluates the specified file.
vars.php <?php
<?php
function foo()
$color = 'green'; {
$fruit = 'apple'; global $color;
?>
*The scope of variables in “included” files depends on where the “include” file is added!
You can use the include_once, require, and require_once statements in similar ways.
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:
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 virtually invisible to the user.
PHP - Sessions
•Sessions store their identifier in a cookie in the client’s 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>
Avoid Error PHP - Sessions
PHP Example: <?php
echo "Look at this nasty error below:<br />";
session_start();
?>
Error!
• 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 = ‘ codd.cs…….. ';
$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 Information
The phpinfo() function is used to output PHP information about the version installed on the
server, parameters selected when installed, etc.
<html><head></head>
<body>
<?php
echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />";
echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />";
echo "User's IP address: " . $_SERVER["REMOTE_ADDR"];
?>
<?php
echo "<br/><br/><br/>";
echo "<h2>All information</h2>";
foreach ($_SERVER as $key => $value) $_SERVER info
{
echo $key . " = " . $value . "<br/>"; on php.net
}
?>
</body>
</html>
The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script.
File Open
The fopen("file_name","mode") function is used to open files in PHP.
<html>
<-- form.html -->
<body>
<form action="welcome.php" method="POST">
Enter your name: <input type="text" name="name" /> <br/>
Enter your age: <input type="text" name="age" /> <br/>
<input type="submit" /> <input type="reset" />
</form>
</body>
</html>
<html>
<!–- welcome.php --> $_POST
<body> contains all POST data.
Welcome <?php echo $_POST["name"].”.”; ?><br />
You are <?php echo $_POST["age"]; ?> years old! $_GET
</body>
contains all GET data.
</html>
Cookie Workings
setcookie(name,value,expire,path,domain) creates cookies.
<?php
setcookie("uname", $_POST["name"], time()+36000);
?>
<html>
<body>
<p>
NOTE:
Dear <?php echo $_POST["name"] ?>, a cookie was set on this setcookie() must appear
page! The cookie will be active when the client has sent the
cookie back to the server. BEFORE <html> (or any
</p>
</body>
output) as it’s part of the
</html> header information sent
with the page.
<html>
<body> $_COOKIE
<?php
if ( isset($_COOKIE["uname"]) )
contains all COOKIE data.
echo "Welcome " . $_COOKIE["uname"] . "!<br />";
else isset()
echo "You are not logged in!<br />"; finds out if a cookie is set
?>
</body>
</html>
use the cookie name as a
variable
Getting Time and Date
date() and time () formats a time or a date.
<?php
//Prints something like: Monday
echo date("l");
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs time() returns
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
current Unix
?> timestamp
Required Fields in User-Entered Data
A multipurpose script which asks users for some basic contact information and then checks to
see that the required fields have been entered.
<html>
<!-- form_checker.php COMP519 -->
<head>
<title>PHP Form example</title>
</head>
<body>
<?php
/*declare some functions*/
Print Function
function print_form($f_name, $l_name, $email, $os)
{
?>
<?php
} //** end of “print_from” function
Check and Confirm Functions
function check_form($f_name, $l_name, $email, $os)
{
if (!$l_name||!$email){
echo "<h3>You are missing some required fields!</h3>";
print_form($f_name, $l_name, $email, $os);
}
else{
confirm_form($f_name, $l_name, $email, $os);
}
} //** end of “check_form” function
<?php
echo "Name: $f_name $l_name <br/>";
echo "Email: $email <br/>";
echo "OS: $os";
} //** end of “confirm_form” function
Main Program
/*Main Program*/
if (!$_POST["submit"])
{
?>
<?php
print_form("","","","");
}
else{
check_form($_POST["f_name"],$_POST["l_name"],$_POST["email"],$_POST["os"]);
}
?>
</body>
</html>
Recommended Texts for Learning
PHP
• Larry Ullman’s 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 you’ve finished the easier books. One of the best
definition/description of object oriented programming I’ve 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/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