Php/Mysql Tutorial: Introduction To Database
Php/Mysql Tutorial: Introduction To Database
Introduction to Database
What is PHP?
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 (cont’d)
Interpreted language, scripts are parsed at run-time
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
3(+1) Tier architecture
voice
DHTML
SMS Remote
services Web Service
SMS system
Client
application
PHP advantage
Any changes to header or footer only require editing of
a single file.
This reduces the amount of work necessary for site
maintenance and redesign.
Helps separate the content and design for easier
maintenance Header
Footer
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
# 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.
Variable usage
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
$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
if (expr) statement
<?php
if ($a > $b) {
echo "a is bigger than b";
$b = $a;
}
?>
<?php
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>
PHP Control Structures
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;
}
PHP Control Structures
<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
default:
echo ‘Enter correct option’;
}
?>
Loops
while (condition) {statements;}
<?php
$count=0;
While($count<3)
{
Print “hello PHP. ”;
$count += 1;
// $count = $count + 1;
// or
// $count++;
?>
Array ( [0] => Array ( [0] => 10 [1] => 20 [2] => 30 )
[1] => Array ( [0] => 40 [1] => 50 [2] => 60 ) )
Arrays
<?php
$x=array(“ab”=>1,array(2,3,4),”cd”=>8);
print_r($x);
?>
Array ( [“ab”] => 1 [0] => Array ( [0] => 2 [1] => 3 [2]
=> 4 ) [”cd”] => 8 )
Arrays
<?php
$x=array(3=>4,array(2,3,4),5);
print_r($x);
?>
Array ( [3] => 4 [4] => Array ( [0] => 2 [1] => 3 [2] =>
4 ) [5] => 5 )
Arrays
Array operations
sort
ksort
rsort
krsort
array_merge
array_combine
array_intersect
Date Display
$datedisplay=date(“yyyy/m/d”);
print $datedisplay;
2009/4/1
$datedisplay=date(“l, F J, Y”);
print $datedisplay;
Day of Month d 01
Day of Month J 1
Day of Week l Monday
Day of Week D Mon
Functions
This inserts files; the code in files will be inserted into current
code.
require is identical to include except upon failure it
will also produce a fatal E_COMPILE_ERROR level error. In
other words, it will halt the script whereas include only
emits a warning (E_WARNING) which allows the script to
continue.
Include Files
The include_once statement includes and evaluates the
specified file during the execution of the script.
This is a behavior similar to the include statement, with
the only difference being that if the code from a file has
already been included, it will not be included again.
The require_once statement is identical to require
except PHP will check if the file has already been included,
and if so, not include (require) it again
PHP - Forms
<?php
if ($_POST["submit"])
echo "<h2>You clicked Submit!</h2>";
else if ($_POST["cancel"])
echo "<h2>You clicked Cancel!</h2>";
?>
</form>
MySQL Connectivity
mysql_connect()
The mysql_connect()function opens a non-persistent
MySQL connection.
This function returns the connection on success, or FALSE
and an error on failure. You can hide the error output by
adding an '@' in front of the function name.
Syntax
mysql_connect(server,user,pwd,newlink,client
flag)
MySQL Connectivity
Parameter Description
server Specifies the server to connect to
user Specifies the username to log in with.
pwd Specifies the password to log in with.
newlink If a second call is made to mysql_connect() with the same
arguments, no new connection will be established; instead, the
identifier of the already opened connection will be returned
clientflag •MYSQL_CLIENT_SSL - Use SSL encryption
•MYSQL_CLIENT_COMPRESS - Use compression protocol
•MYSQL_CLIENT_IGNORE_SPACE - Allow space after function
names
•MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout
seconds of inactivity before closing the connection
MySQL Connectivity
Example:
<?php
$con =
mysql_connect("localhost","mysql_user","mysq
l_pwd");
if (!$con){
die('Could not connect: ‘.mysql_error());
}
echo 'Connected successfully';
mysql_close($con);
?>
MySQL Connectivity
mysql_close()
The mysql_close() function closes a non-persistent
MySQL connection.
This function returns TRUE on success, or FALSE on failure.
Syntax:
mysql_close(connection)
Parameter Description
connection Specifies the MySQL connection to close. If not
specified, the last connection opened by
mysql_connect() is used.
MySQL Connectivity
mysql_select_db()
The mysql_select_db() function sets the active MySQL
database.
This function returns TRUE on success, or FALSE on failure.
Syntax:
mysql_select_db(database,connection)
Parameter Description
database Required. Specifies the database to select.
connection Optional. Specifies the MySQL connection. If not
specified, the last connection opened by
mysql_connect() or mysql_pconnect() is used.
MySQL Connectivity
<?php
$con = mysql_connect("localhost", “root",
“admin");
if (!$con){
die('Could not connect: '.
mysql_error());
}
$db_selected = mysql_select_db("test_db",
$con);
if (!$db_selected){
die ("Can\'t use test_db : “.
mysql_error());
}
mysql_close($con);
?>
MySQL Connectivity
mysql_query()
The mysql_query() function executes a query on a
MySQL database.
This function returns the query handle for SELECT queries,
TRUE/FALSE for other queries, or FALSE on failure.
Syntax
mysql_query(query,connection)
Parameter Description
query Required. Specifies the SQL query to send (should
not end with a semicolon)
connection Optional. Specifies the MySQL connection. If not
specified, the last connection opened by
mysql_connect() or mysql_pconnect() is used.
MySQL Connectivity
<?php
$con =
mysql_connect("localhost",”root",”admin");
if (!$con){
die('Could not connect: ' . mysql_error());
}
$sql = "CREATE DATABASE my_db";
if (mysql_query($sql,$con)){
echo "Database my_db created";
}
else{
echo "Error creating database:" .
mysql_error();
}
?>
MySQL Connectivity
<?php
$con = mysql_connect("localhost", “root",
“admin");
if (!$con){
die('Could not connect: '. mysql_error());
}
$db_selected = mysql_select_db("test_db", $con);
if (!$db_selected){
die ("Can\'t use test_db : “. mysql_error());
}
$sql="SELECT * FROM Person where name=‘$uname’";
mysql_query($sql,$con);
mysql_close($con);
?>
MySQL Connectivity
mysql_fetch_array()
The mysql_fetch_array() function returns a row from a
recordset as an associative array and/or a numeric array.
This function gets a row from the mysql_query() function
and returns an array on success, or FALSE on failure or when
there are no more rows.
Syntax
mysql_fetch_array(data,array_type)
MySQL Connectivity
Parameter Description
data Required. Specifies which data pointer to use. The data
pointer is the result from the mysql_query() function
array_type Optional. Specifies what kind of array to return.Possible
values:
•MYSQL_ASSOC - Associative array
•MYSQL_NUM - Numeric array
•MYSQL_BOTH - Default. Both associative and numeric
array
MySQL Connectivity
mysql_fetch_row()
The mysql_fetch_row() function returns a row
from a recordset as a numeric array.
This function gets a row from the mysql_query()
function and returns an array on success, or FALSE on
failure or when there are no more rows.
Syntax
mysql_fetch_row(data)
Parameter Description
data Required. Specifies which data pointer to use. The data
pointer is the result from the mysql_query() function
MySQL Connectivity
<?php
echo "<table>";
while ($row = mysql_fetch_row($result)) {
echo "<tr><td>".$row[0]
."</td><td>".$row[1].
"</td><td>".$row[2]."</td><td>".
$row[3]."</td></tr>";
}
echo "</table>";
?>
MySQL Connectivity
<?php
echo "<table>";
while ($row = mysql_fetch_array($result))
{
echo "<tr><td>{$row[‘ID’]}
</td><td>{$row[1]}
</td><td>{$row[2]}</td><td>
${row[‘mailid’]}</td></tr>";
}
echo "</table>";
?>
Cookies
The setcookie() function is used to create cookies.
Should be called before <html> tag.
setcookie(name, [value], [expire],
[path], [domain], [secure]);
<?php setcookie("uname", $name, time()
+36000); ?>
This sets a cookie named "uname" - that expires after ten
hours.
Either a blank value or a time in the past makes the cookie
expired.
Cookies
To access a cookie, refer to the cookie name as a variable or use
$_COOKIE array. The isset() checks whether the cookie is
set or not
<html> <body>
<?php
if (isset($uname))// isset($_Cookie[$uname])
echo "Welcome " . $_Cookie[$uname].
"!<br />";
else
echo "You are not logged in!<br />"; ?>
?>
</body> </html>
Cookies
Benefit of Cookies
Cookies are used for authenticating, tracking, and
maintaining specific information about users
Personolised home pages
Electronic shopping carts.
Why use sessions
A normal HTML website will not pass data from one
page to another
All information is forgotten when a new page is loaded
Many websites need to pass user data from one page to
another
for tasks like a shopping cart, which requires data(the user's
selected product) to be remembered from one page to the
next
Using PHP sessions is one solution.
Sessions
The session_start() function is used to create a
session. Should be called before <html> tag.
<?php
session_start();
?>
Sessions
<?php
session_start();
if (!isset($_SESSION['count']))
$_SESSION['count'] = 0;
else
$_SESSION['count']++;
?>
Sessions
session_unregister(´varname´); unregisters
a session variable
session_destroy() destroys a session